在我的项目中,我使用http POST方法将json值发布到我的服务器。但在发布时我收到此错误消息:
W/System.err: java.io.FileNotFoundException: http://10.1.7.95:2403/beacons
W/System.err: at com.android.okhttp.internal.huc.HttpURLConnectionImpl.getInputStream(HttpURLConnectionImpl.java:238)
W/System.err: at com.beaconsapptwo.estimote.NetworkMgr.callPostMethod(NetworkMgr.java:110)
W/System.err: at com.beaconsapptwo.MainActivity$2.onClick(MainActivity.java:235)
W/System.err: at android.view.View.performClick(View.java:5204)
W/System.err: at android.view.View$PerformClick.run(View.java:21153)
W/System.err: at android.os.Handler.handleCallback(Handler.java:739)
W/System.err: at android.os.Handler.dispatchMessage(Handler.java:95)
W/System.err: at android.os.Looper.loop(Looper.java:148)
W/System.err: at android.app.ActivityThread.main(ActivityThread.java:5417)
W/System.err: at java.lang.reflect.Method.invoke(Native Method)
W/System.err: at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:726)
W/System.err: at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:616)
我的PostMethod是这样的:
public static String callPostMethod(String urlString ,String Json){
Log.d(TAG,"URL going to call " + urlString + ":::"+Json );
HttpURLConnection httpcon;
URL url = null;
String result = null;
try{
url = new URL(urlString.toString());
httpcon = (HttpURLConnection) url.openConnection();
httpcon.setDoOutput(true);
httpcon.setRequestProperty("Content-Type", "application/json");
httpcon.setRequestProperty("Accept", "application/json");
httpcon.setRequestMethod("POST");
httpcon.connect();
//Write
OutputStream os = httpcon.getOutputStream();
BufferedWriter writer = new BufferedWriter(new OutputStreamWriter(os, "UTF-8"));
writer.write(Json);
writer.close();
os.close();
//Read
BufferedReader br = new BufferedReader(new InputStreamReader(httpcon.getInputStream(),"UTF-8"));
String line = null;
StringBuilder sb = new StringBuilder();
while ((line = br.readLine()) != null) {
sb.append(line);
}
br.close();
result = sb.toString();
} catch (UnsupportedEncodingException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
return result;
}
这是Json数据:
{
"uuid": "B9402F30-F5F8-466E-AFI9-25556B57FE6D",
"minor": "43406",
"major": "23236",
"title": "Virtual Beacon",
"message": "Virtual Beacon message"
}
我哪里错了?
答案 0 :(得分:0)
您永远不会将HttpURLConnection
设置为允许输入。尝试在httpcon.setDoInput(true);
设置中设置HttpURLConnection
。
此外,您可以尝试删除行httpcon.setRequestMethod("POST");
调用httpcon.setDoOutput(true);
已将您的连接方法默认为POST,因此不需要。另外,setRequestMethod()
根据文档用于其他设置:
HttpURLConnection默认使用GET方法。它将使用POST if setDoOutput(true)已被调用。其他HTTP方法(OPTIONS,HEAD, PUT,DELETE和TRACE)可以与setRequestMethod(String)一起使用。