我正在制作Android应用程序而且我遇到了一些问题。
我正在做的是尝试从连接到数据库的远程服务器上的PHP文件中获取信息。但是我在Logcat中得到Exception: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());
}
&#39; System.out.println(&#34; 1&#34;);&#39;用于调试。
我的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);
我不知道发生了什么,是的,我确实拥有适当的权限!
答案 0 :(得分:1)
你是从主线程运行的吗?
Android不允许您在主线程上执行长时间运行的操作(如HTTP请求等网络操作)。 Android documentation
答案 1 :(得分:0)
问题可能与多部分实体有关,请参阅下面的代码。经过测试。调整它以满足您的需求。
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;
}