【发布时间】:2017-05-04 09:36:04
【问题描述】:
这是我的问题: 我有一个向服务器发出发布请求的功能,我在http://hmkcode.appspot.com/post-json/index.html 上对其进行了测试,它似乎工作得很好。但是当我在我自己的服务器上尝试它应该接收特定的发布请求(json)并给我一些 json 时,它不会向我发送任何东西。我的问题一定是我发送的,但我找不到错误,所以您可以在 POST 时检查完整的 URL(例如使用调试器)吗?示例: "http://example.com/receive/data?{"id"=12,"name"="example"}" 。这是我的代码:
protected String doInBackground(String... strJson ) {
URL url;
String response = "";
try {
url = new URL(SERVER);
HttpURLConnection conn = (HttpURLConnection) url.openConnection();
conn.setReadTimeout(15000);
conn.setConnectTimeout(15000);
conn.setRequestProperty("Content-Type", "application/json");
conn.setRequestProperty("Accept", "application/json");
conn.setRequestMethod("POST");
conn.setDoInput(true);
conn.setDoOutput(true);
OutputStream os = conn.getOutputStream();
BufferedWriter writer = new BufferedWriter( new OutputStreamWriter(os, "UTF-8"));
writer.write(strJson[0]);
writer.flush();
writer.close();
os.close();
int responseCode=conn.getResponseCode();
if (responseCode == HttpsURLConnection.HTTP_OK) {
String line;
BufferedReader br=new BufferedReader(new InputStreamReader(conn.getInputStream()));
while ((line=br.readLine()) != null) {
response+=line;
}
}
else {
response="NO HTTP_OK : " + responseCode;
}
conn.disconnect();
} catch (MalformedURLException e) {
response = "malformedURL" + e.toString();
} catch (ProtocolException e) {
response = "Protocol" + e.toString();
} catch (IOException e) {
response = "IOException" + e.toString();
} catch (Exception e) {
e.printStackTrace();
response = "Exception" + e.toString();
}
return response;
}
【问题讨论】:
-
url.toString()? -
Log.d("debugurl",url.toString());呢? -
Log.e("url","...."+url.tostring());然后检查你的日志。
-
@Denny no 当我执行 url.toString() 时,它会显示“example.com/receive/data”,但不会显示我发出的帖子请求
-
您可以使用 Volley 发送 POST 请求:androidhive.info/2014/05/android-working-with-volley-library-1