【问题标题】:response=httpClient.execute(request) keeps giving NetworkOnMainThreadException [duplicate]response=httpClient.execute(request) 不断给出 NetworkOnMainThreadException [重复]
【发布时间】:2015-11-09 22:49:10
【问题描述】:

我已经尝试了几个小时向 php 发送 POST 请求,该 php 发送回 json 响应。但是那一行代码一直给我带来问题,我似乎无法继续前进。我很沮丧。我已经查找了无数使用同一行的其他示例!但由于某种原因,它对我不起作用! 这是我的 doinBackgrounds 的代码 sn-p:

protected Void doInBackground(Void... voids) {
    HttpClient httpClient=new DefaultHttpClient();
    HttpGet request=new HttpGet();
    BufferedReader in=null;
    String data=null;
    HttpResponse response = null;
    try {
        URI website=new URI("login.php");
        request.setURI(website);
    } catch (URISyntaxException e) {
        e.printStackTrace();
    }

    HttpPost httpPost=new HttpPost("login.php");
    List<NameValuePair> nameValuePairs=new ArrayList<NameValuePair>(2);
    nameValuePairs.add(new BasicNameValuePair("name", name));
    nameValuePairs.add(new BasicNameValuePair("password", pwd));
    try {
        httpPost.setEntity(new UrlEncodedFormEntity(nameValuePairs));
    } catch (UnsupportedEncodingException e) {
        e.printStackTrace();
    }
    try {
        response=httpClient.execute(request);
    } catch (IOException e) {
        e.printStackTrace();
    }
    try {
        in=new BufferedReader(new InputStreamReader(response.getEntity().getContent()));
    } catch (IOException e) {
        e.printStackTrace();
    }
    try {
        String line=in.readLine();
        System.out.println(line);
    } catch (IOException e) {
        e.printStackTrace();
    }

    if (Utility.isNotNull(name) && Utility.isNotNull(pwd)) {
        RequestParams params = new RequestParams();
        if (Utility.validate(name, pwd)) {
            params.put("username", name);
            params.put("password", pwd);
            bloggedIn=true;
            onPostExecute();
        } else {
            loginActivity.InvalidToast();
        }
    } else {
        loginActivity.EmptyToast();
    }
    return null;
}

【问题讨论】:

  • 请发布您的NetworkOnMainThreadException 的整个堆栈跟踪。
  • @CommonsWare 我已经编辑了问题

标签: java php android apache-httpclient-4.x jsonresponse


【解决方案1】:

你自己打电话给doInBackground()。这不是您使用AsyncTask 的方式。要执行AsyncTask,请创建一个实例并在其上调用execute()executeOnExecutor()。这将导致doInBackground() 在后台线程上运行。

您可以在the JavaDocs 中阅读有关AsyncTask 的更多信息。

(顺便说一句,将来,请将堆栈跟踪作为从 LogCat 复制的文本发布,而不是屏幕截图)

【讨论】:

  • 谢谢,对我来说效果很好
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2011-07-06
  • 2018-01-12
  • 1970-01-01
相关资源
最近更新 更多