在android中使用restweb服务
我正在使用一个REST Web服务,它返回一个JSON字典,但是当我调用它时,应用程序崩溃了在android中使用restweb服务,android,rest,Android,Rest,我正在使用一个REST Web服务,它返回一个JSON字典,但是当我调用它时,应用程序崩溃了 HttpResponse resp = httpClient.execute(post); 这是我的代码: System.out.println("onClick!!!"); HttpClient httpClient = new DefaultHttpClient(); HttpPost post = new HttpPost("http://applocalize.
HttpResponse resp = httpClient.execute(post);
这是我的代码:
System.out.println("onClick!!!");
HttpClient httpClient = new DefaultHttpClient();
HttpPost post = new HttpPost("http://applocalize.com.br/rest/rest.php");
post.setHeader("content-type", "application/json; charset=UTF-8");
post.setHeader("Accept", "application/json");
//Construimos el objeto cliente en formato JSON
JSONObject dato = new JSONObject();
try {
dato.put("pg","categorias");
dato.put("serv", "buscar");
dato.put("dt_atualizacao", "");
StringEntity entity = new StringEntity(dato.toString());
post.setEntity(entity);
HttpResponse resp = httpClient.execute(post);
String respStr = EntityUtils.toString(resp.getEntity());
System.out.println("OKAY!");
} catch (ClientProtocolException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
} catch (JSONException e) {
e.printStackTrace();
}
}
日志:
28517-28517/com.allapps.localizeapp E/AndroidRuntime﹕ FATAL EXCEPTION: main
java.lang.RuntimeException: Unable to start activity ComponentInfo{com.allapps.localizeapp/com.allapps.localizeapp.MapsActivity}: android.os.NetworkOnMainThreadException
at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2252)
at
基本上,您需要在后台线程中执行网络请求。有多篇其他SO文章详细介绍了如何做到这一点,例如: 使用处理程序的示例:
android文档中的一些信息:您不能使用主UI线程运行web服务,所以请使用Ansynctask:
new AsyncTask<Void, Void, String>() {
@Override
protected String doInBackground(Void... params) {
//put your web service here
return result;
}
@Override
protected void onPostExecute(String result) {
//here do something with main UI thread
}
}.execute(null, null, null);
newasynctask(){
@凌驾
受保护字符串doInBackground(无效…参数){
//将您的web服务放在这里
返回结果;
}
@凌驾
受保护的void onPostExecute(字符串结果){
//这里使用主UI线程执行一些操作
}
}.执行(空,空,空);
发生了什么错误?Logcat?异常名称可能重复+谷歌=无数答案。