我的代码一直在崩溃,我无法找到确切的问题。任何人都可以说这是使用XML数据的正确方法吗?
public class MainActivity extends Activity {
TextView result;
@Override
protected void onCreate(Bundle savedInstanceState)
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
result = (TextView)findViewById(R.id.result);
HttpClient httpClient = new DefaultHttpClient();
HttpPost request = new HttpPost("http://localhost:8282/attendance/jnd/mark");
try {
StringEntity se = new StringEntity( "<?xml version=\"1.0\" encoding=\"utf-8\"?><Attendance type=\"2\" ><sch id=\"7\"/> </Attendance>", HTTP.UTF_8);
se.setContentType("text/xml");
request.setEntity(se);
HttpResponse httpresponse = httpClient.execute(request);
HttpEntity resEntity = httpresponse.getEntity();
result.setText(EntityUtils.toString(resEntity));
} catch (ClientProtocolException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
logcat的:
07-31 13:44:13.533:D / AndroidRuntime(2567):---------崩溃开始 07-31 13:44:13.533:E / AndroidRuntime(2567):致命异常:主要 07-31 13:44:13.533:E / AndroidRuntime(2567):进程:comorg.demoapi,PID:2567 07-31 13:44:13.533:E / AndroidRuntime(2567):java.lang.RuntimeException:无法启动活动ComponentInfo {comorg.demoapi / comorg.demoapi.MainActivity}:android.os.NetworkOnMainThreadException 07-31 13:44:13.533:E / AndroidRuntime(2567):在android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2298) 07-31 13:44:13.533:E / AndroidRuntime(2567):在android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2360)
答案 0 :(得分:0)
我强烈建议您使用AndroidHttpRestService。
它非常简单,为您做了很多工作。
https://github.com/matessoftwaresolutions/AndroidHttpRestService
它允许您使用Get / posts,JSON通信等。
编辑:
看到你的例外,我可以说这很容易。您无法在主线程(UI线程)上发出请求。把你的代码放在异步任务中,这就是!!