我只是:
HttpClient httpClient = new DefaultHttpClient();
// Creating HTTP Post
HttpPost httpPost = new HttpPost(
"http://www.google.com/");
// Making HTTP Request
try {
HttpResponse response = (HttpResponse) httpClient.execute(httpPost);
// writing response to log
Log.d("Http Response:", response.toString());
} catch (ClientProtocolException e) {
// writing exception to log
e.printStackTrace();
} catch (IOException e) {
// writing exception to log
e.printStackTrace();
}
但是当我运行应用程序时,它会崩溃并且无法正常工作。
这是我的日志:
02-05 14:33:42.217: E/AndroidRuntime(25026): java.lang.RuntimeException: Unable to start activity ComponentInfo{com.app.myapppp/com.app.myapppp.Main}: android.os.NetworkOnMainThreadException
02-05 14:33:42.217: E/AndroidRuntime(25026): at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2110)
02-05 14:33:42.217: E/AndroidRuntime(25026): at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2135)
02-05 14:33:42.217: E/AndroidRuntime(25026): at android.app.ActivityThread.access$700(ActivityThread.java:140)
02-05 14:33:42.217: E/AndroidRuntime(25026): at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1237)
02-05 14:33:42.217: E/AndroidRuntime(25026): at android.os.Handler.dispatchMessage(Handler.java:99)
02-05 14:33:42.217: E/AndroidRuntime(25026): at android.os.Looper.loop(Looper.java:137)
02-05 14:33:42.217: E/AndroidRuntime(25026): at android.app.ActivityThread.main(ActivityThread.java:4921)
02-05 14:33:42.217: E/AndroidRuntime(25026): at java.lang.reflect.Method.invokeNative(Native Method)
02-05 14:33:42.217: E/AndroidRuntime(25026): at java.lang.reflect.Method.invoke(Method.java:511)
02-05 14:33:42.217: E/AndroidRuntime(25026): at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:1038)
02-05 14:33:42.217: E/AndroidRuntime(25026): at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:805)
02-05 14:33:42.217: E/AndroidRuntime(25026): at dalvik.system.NativeStart.main(Native Method)
02-05 14:33:42.217: E/AndroidRuntime(25026): Caused by: android.os.NetworkOnMainThreadException
02-05 14:33:42.217: E/AndroidRuntime(25026): at android.os.StrictMode$AndroidBlockGuardPolicy.onNetwork(StrictMode.java:1118)
02-05 14:33:42.217: E/AndroidRuntime(25026): at java.net.InetAddress.lookupHostByName(InetAddress.java:385)
02-05 14:33:42.217: E/AndroidRuntime(25026): at java.net.InetAddress.getAllByNameImpl(InetAddress.java:236)
02-05 14:33:42.217: E/AndroidRuntime(25026): at java.net.InetAddress.getAllByName(InetAddress.java:214)
02-05 14:33:42.217: E/AndroidRuntime(25026): at org.apache.http.impl.conn.DefaultClientConnectionOperator.openConnection(DefaultClientConnectionOperator.java:137)
02-05 14:33:42.217: E/AndroidRuntime(25026): at org.apache.http.impl.conn.AbstractPoolEntry.open(AbstractPoolEntry.java:164)
02-05 14:33:42.217: E/AndroidRuntime(25026): at org.apache.http.impl.conn.AbstractPooledConnAdapter.open(AbstractPooledConnAdapter.java:119)
02-05 14:33:42.217: E/AndroidRuntime(25026): at org.apache.http.impl.client.DefaultRequestDirector.execute(DefaultRequestDirector.java:360)
02-05 14:33:42.217: E/AndroidRuntime(25026): at org.apache.http.impl.client.AbstractHttpClient.execute(AbstractHttpClient.java:670)
02-05 14:33:42.217: E/AndroidRuntime(25026): at org.apache.http.impl.client.AbstractHttpClient.execute(AbstractHttpClient.java:509)
02-05 14:33:42.217: E/AndroidRuntime(25026): at org.apache.http.impl.client.AbstractHttpClient.execute(AbstractHttpClient.java:487)
02-05 14:33:42.217: E/AndroidRuntime(25026): at com.app.myapppp.Main.onCreate(Main.java:133)
02-05 14:33:42.217: E/AndroidRuntime(25026): at android.app.Activity.performCreate(Activity.java:5206)
02-05 14:33:42.217: E/AndroidRuntime(25026): at android.app.Instrumentation.callActivityOnCreate(Instrumentation.java:1094)
02-05 14:33:42.217: E/AndroidRuntime(25026): at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2074)
02-05 14:33:42.217: E/AndroidRuntime(25026): ... 11 more
答案 0 :(得分:0)
使用像Example
这样的AsyncTask进行API调用点击API调用或在Main方法中
public void onClick(View v) {
// TODO Auto-generated method stub
if(value.getText().toString().length()<1){
// out of range
Toast.makeText(this, "please enter something", Toast.LENGTH_LONG).show();
}else{
pb.setVisibility(View.VISIBLE);
new MyAsyncTask().execute(value.getText().toString());
}
}
AsynckTask
private class MyAsyncTask extends AsyncTask<String, Integer, Double>{
@Override
protected Double doInBackground(String... params) {
// TODO Auto-generated method stub
postData(params[0]);
return null;
}
}
// MyAsyncTask
private class MyAsyncTask extends AsyncTask<String, Integer, Double>{
@Override
protected Double doInBackground(String... params) {
// TODO Auto-generated method stub
postData(params[0]);
return null;
}
protected void onPostExecute(Double result){
pb.setVisibility(View.GONE);
Toast.makeText(getApplicationContext(), "command sent", Toast.LENGTH_LONG).show();
}
protected void onProgressUpdate(Integer... progress){
pb.setProgress(progress[0]);
}
}
您的API调用方法
public void postData(String valueIWantToSend) {
HttpClient httpclient = new DefaultHttpClient();
// specify the URL you want to post to
HttpPost httppost = new HttpPost("http://www.google.com/");
try {
// create a list to store HTTP variables and their values
List nameValuePairs = new ArrayList();
// add an HTTP variable and value pair
nameValuePairs.add(new BasicNameValuePair("myHttpData", valueIwantToSend));
httppost.setEntity(new UrlEncodedFormEntity(nameValuePairs));
// send the variable and value, in other words post, to the URL
HttpResponse response = httpclient.execute(httppost);
} catch (ClientProtocolException e) {
// process execption
} catch (IOException e) {
// process execption
}
}
答案 1 :(得分:0)
这种情况正在发生,因为您尝试在主要活动中执行与网络相关的操作。 这是不允许的,而不是做网络相关任务的坏方法。 要完成所有这样的任务,还有其他方法,例如AsyncTask类可以做到这一点。
这使您可以在应用程序的后台执行所有这些重大任务。 这样你的主线程就不会忙碌,这显然会导致你的应用程序崩溃。
文档http://developer.android.com/reference/android/os/AsyncTask.html
简单的asyncTask示例http://programmerguru.com/android-tutorial/android-asynctask-example/
答案 2 :(得分:0)
需要在单独的线程中执行网络操作。
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
new NetworkOperation().execute();
}
异步任务示例
private class NetworkOperation extends AsyncTask<String, Void, String> {
@Override
protected String doInBackground(String... params) {
HttpClient httpClient = new DefaultHttpClient();
// Creating HTTP Post
HttpPost httpPost = new HttpPost(
"http://www.google.com/");
// Making HTTP Request
try {
HttpResponse response = (HttpResponse) httpClient.execute(httpPost);
// writing response to log
Log.d("Http Response:", response.toString());
} catch (ClientProtocolException e) {
// writing exception to log
e.printStackTrace();
} catch (IOException e) {
// writing exception to log
e.printStackTrace();
}
return "";
}
@Override
protected void onPostExecute(String result) {
}
@Override
protected void onPreExecute() {
}
@Override
protected void onProgressUpdate(Void... values) {
}
}