0

我开发了 android 应用程序,一切都是正确的,没有错误,但是当我运行代码时,我在下面发现了这个错误,当我跟踪代码时,它停在这一行:

HttpResponse httpResponse = httpClient.execute(httpPost);

代码的一部分:

try {
        // defaultHttpClient

        DefaultHttpClient httpClient = new DefaultHttpClient();
        HttpPost httpPost = new HttpPost(url);
        httpPost.setEntity(new UrlEncodedFormEntity(params));
        Log.d("w", "2a json...................");
        HttpResponse httpResponse = httpClient.execute(httpPost);
        Log.d("w", "2b json...................");
        HttpEntity httpEntity = httpResponse.getEntity();
        Log.d("w", "2c json...................");
        is = httpEntity.getContent();
        Log.d("w", "3 json...................");
    } catch (UnsupportedEncodingException e) {
        e.printStackTrace();
    } catch (ClientProtocolException e) {
        e.printStackTrace();
    } catch (IOException e) {
        e.printStackTrace();
    }

错误:

threadid=1: thread exiting with uncaught exception (group=0x410702a0)
FATAL EXCEPTION: main
android.os.NetworkOnMainThreadException
    at android.os.StrictMode$AndroidBlockGuardPolicy.onNetwork(StrictMode.java:1118)
    at libcore.io.BlockGuardOs.connect(BlockGuardOs.java:84)
    at libcore.io.IoBridge.connectErrno(IoBridge.java:127)
    at libcore.io.IoBridge.connect(IoBridge.java:112)
    at java.net.PlainSocketImpl.connect(PlainSocketImpl.java:192)
at java.net.PlainSocketImpl.connect(PlainSocketImpl.java:459)
    at java.net.Socket.connect(Socket.java:842)
    at org.apache.http.conn.scheme.PlainSocketFactory.connectSocket(PlainSocketFactory.java:119)
4

1 回答 1

0

创建一个 Asynctask 并在 doInBackground 方法中进行网络调用

这是你的代码

class ABCTask extends AsyncTask<String, Void, Void> {

    private Exception exception;

    protected void doInBackground(String... urls) {
       try {
        // defaultHttpClient

        DefaultHttpClient httpClient = new DefaultHttpClient();
        HttpPost httpPost = new HttpPost(url);
        httpPost.setEntity(new UrlEncodedFormEntity(params));
        Log.d("w", "2a json...................");
        HttpResponse httpResponse = httpClient.execute(httpPost);
        Log.d("w", "2b json...................");
        HttpEntity httpEntity = httpResponse.getEntity();
        Log.d("w", "2c json...................");
        is = httpEntity.getContent();
        Log.d("w", "3 json...................");
    } catch (UnsupportedEncodingException e) {
        e.printStackTrace();
    } catch (ClientProtocolException e) {
        e.printStackTrace();
    } catch (IOException e) {
        e.printStackTrace();
    }
    }

    protected void onPostExecute() {

// write what u want to do after completion of the doInBackground method
    }
 }

 new ABCTask().execute();
于 2013-03-15T17:07:25.107 回答