我正在制作一个Android应用程序,我遇到了一些小问题。
我正在做的是尝试从连接到DB的远程服务器上的PHP文件中获取信息。但是,在Logcat中,我得到了异常: null,我的代码:
httpclient=new DefaultHttpClient();
System.out.println("1");
httppost= new HttpPost("MYSITE/MYPHP.PHP");
System.out.println("1");
nameValuePairs = new ArrayList<NameValuePair>(1);
System.out.println("1");
nameValuePairs.add(new BasicNameValuePair("uid",userConfig.uid));
System.out.println("1");
httppost.setEntity(new UrlEncodedFormEntity(nameValuePairs));
System.out.println("1");
response=httpclient.execute(httppost);
System.out.println("1");
ResponseHandler<String> responseHandler = new BasicResponseHandler();
System.out.println("1");
final String response = httpclient.execute(httppost, responseHandler);
System.out.println("Response: " + response);
runOnUiThread(new Runnable() {
public void run() {
System.out.println("Response: " + response);
dialog.dismiss();
}
});
}catch(Exception e){
System.out.println("Exception: " + e.getMessage());
}
“System.out.println(”1“);”用于调试。
我的logcat输出
10-10 22:53:44.382 24228-24228/PACKAGENAME I/System.out﹕ 1
10-10 22:53:44.382 24228-24228/PACKAGENAME I/System.out﹕ 1
10-10 22:53:44.382 24228-24228/PACKAGENAME I/System.out﹕ 1
10-10 22:53:44.382 24228-24228/PACKAGENAME I/System.out﹕ 1
10-10 22:53:44.383 24228-24228/PACKAGENAME I/System.out﹕ 1
10-10 22:53:44.407 24228-24228/PACKAGENAME I/System.out﹕ Exception: null
所以你可以看到它得到了这条线
response=httpclient.execute(httppost);
我不知道发生了什么,是的,我确实有适当的许可!
发布于 2014-10-11 03:43:10
你是从主线程运行这个的吗?
Android不允许在主线程上执行长时间运行的操作(比如网络操作,比如HTTP请求)。Android文档
发布于 2014-10-11 04:04:02
问题可能与多部分实体有关,请参阅下面的代码。测试过了。根据你的需要调整。
public static String post(String url, String imagePath, String apikey) {
String response = null;
try {
DefaultHttpClient httpClient = new DefaultHttpClient();
HttpPost httpPost = new HttpPost(url);
MultipartEntityBuilder entity = MultipartEntityBuilder.create();
entity.addPart("xyz", new FileBody(new File(imagePath)));
entity.addPart("abc", new StringBody(apikey,
ContentType.TEXT_PLAIN));
httpPost.setEntity(entity.build());
HttpResponse httpResponse = httpClient.execute(httpPost);
HttpEntity httpEntity = httpResponse.getEntity();
response = EntityUtils.toString(httpEntity);
} catch (UnsupportedEncodingException e) {
e.printStackTrace();
} catch (ClientProtocolException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
return response;
}
https://stackoverflow.com/questions/26310617
复制相似问题