我正在向具有一些 php 脚本以返回一些数据的 Web 服务器发出发布请求。
当我在我的真实手机中运行代码时,代码运行良好。在模拟器上测试时,它不起作用。它抛出“空指针异常”。exception.getMessage() 告诉 NULL
我还尝试通过从浏览器应用程序直接在模拟器中请求 url 来访问该服务器,并且它工作正常。当然,我收到了没有发送任何帖子数据的错误,因为我没有发送任何帖子参数,但它是可以访问的。我一开始遇到证书错误,但单击确定后它就起作用了。
尝试连接到我的开发机器上的本地服务器(10.0.2.2)时,我遇到了同样的问题。我认为问题出在配置中,所以我将其上传到 Web 服务器,但仍然遇到同样的问题:
public String postData(ArrayList<String> params) {
String responseText=null;
// Create a new HttpClient and Post Header
HttpClient httpclient = new DefaultHttpClient();
HttpPost httppost = new HttpPost(SERVERURL);
Log.i(TAG, "Posting HttpPost .. . ");
//goes well till this line
try {
// Add your data
List<NameValuePair> nameValuePairs = new ArrayList<NameValuePair>(2);
nameValuePairs.add(new BasicNameValuePair("long", params.get(0)));
nameValuePairs.add(new BasicNameValuePair("lat", params.get(1)));
httppost.setEntity(new UrlEncodedFormEntity(nameValuePairs));
// Execute HTTP Post Request
HttpResponse response = httpclient.execute(httppost);
Log.i(TAG, "Posting httpclient.execute .. . ");
responseText = convertStreamToString(response.getEntity().getContent());
//responseText = EntityUtils.toString(response.getEntity());
if (responseText !=null) {
Log.i(TAG,"PRESPONSE TEXT:"+ responseText);
}
else
Log.i(TAG," Entity RESPONSE is NULL");
} catch (ClientProtocolException e) {
Log.i(TAG, " POST ClientProtocolException " +e.getMessage());
} catch (IOException e) {
Log.i(TAG, " POST IOException " +e.getMessage());
} catch (Exception el) {
Log.i(TAG, " POST Exception " +el.getMessage());
}
return responseText;
}