我试图在java上使用HttpRequest方法,但它不起作用,这是我的代码
package com.example.phpconnect;
import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.client.HttpClient;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.util.EntityUtils;
import android.util.Log;
public class httpHandler {
public String post(String posturl){
try{
HttpClient httpclient = new DefaultHttpClient();
HttpPost httppost = new HttpPost(posturl);
Log.w("Se envio","Fase 1");
HttpResponse resp = httpclient.execute(httppost);
HttpEntity ent = resp.getEntity();
Log.w("Se envio","Fase 2");
String text = EntityUtils.toString(ent);
Log.w("Se envio","Fase 3");
return text;
}
catch(Exception e){
Log.w("Se envio","Error");
return "Error";
}
}
}
它可以正常工作到第一个日志,然后它会抛出错误,请有人知道问题出在哪里?谢谢!
答案 0 :(得分:0)
当应用程序尝试在其主线程上执行网络操作时,抛出NetworkOnMainThreadException。
正如@EJP在评论中正确指出的那样,只会尝试详细说明。
不应在主线程中执行HTTP Post请求。它需要在后台运行,为此你可以使用AsyncTask并在doInBackground()
中执行它。