【问题标题】:Android Async HttpUrlConnection requestAndroid 异步 HttpUrlConnection 请求
【发布时间】:2014-01-24 11:27:56
【问题描述】:

我有这个发送登录请求的代码:

@Override
public void onClick(View arg0) {

    switch(arg0.getId()) {

        case R.id.signInButton: 
            new AsyncSignIn().execute();
            break;

        default: 
            break;
    }
}

private class AsyncSignIn extends AsyncTask<Void, Void, Void> {

    protected Void doInBackground(Void...voids) {
        try {
            String email = eField.getText().toString();
            String password = pField.getText().toString();
            if(isOnline(getApplicationContext())) {
                if(!Requester.signIn(email, password)) {
                    makeToast("Неверный логин или пароль.");
                }
                else {
                    _userEmail = email;
                    startMainContentActivity();
                }
            }
            else {
                makeToast("Нет доступа к интернету.");
            }
        } catch (IOException e) {
            e.printStackTrace();
        }           
        return null;
    }

}

但是除了 NetworkOnMainThread 之外,应用程序崩溃了:

01-24 20:04:15.248: E/AndroidRuntime(758): android.os.NetworkOnMainThreadException

实际上在这个字符串中,“handle”是一个 HttpURLConnection 对象:

 DataOutputStream writer = new DataOutputStream(handle.getOutputStream());

我已经尝试过为此使用 Handler,但结果相同。怎么了?

更新

这是一个发送登录请求的函数:

protected String sendPost(String _url, String _urlParameters) throws IOException {
    URL url = new URL(_url);
    HttpURLConnection handle = (HttpURLConnection) url.openConnection();
    handle.setRequestMethod("POST");
    handle.setRequestProperty("Host", Host);
    handle.setRequestProperty("Content-Type", POSTContentType);
    handle.setRequestProperty("Content-Length", ""+_urlParameters.getBytes().length);
    handle.setRequestProperty("User-Agent", UserAgent);
    handle.setRequestProperty("Accept", Accept);
    handle.setRequestProperty("Accept-Language", AcceptLang);
    handle.setRequestProperty("Connection", Connection);
    handle.setUseCaches(false);
    handle.setDoOutput(true);
    handle.setDoInput(true);

    DataOutputStream writer = new DataOutputStream(handle.getOutputStream()); //App crashed string
    writer.writeBytes(_urlParameters);
    writer.flush();
    writer.close();
    int responseCode = handle.getResponseCode();

    if(responseCode == 200) {       
        BufferedReader reader = new BufferedReader(new InputStreamReader(handle.getInputStream())); 
        String inputLine;
        StringBuffer response = new StringBuffer();

        while((inputLine = reader.readLine()) != null) {
            response.append(inputLine);
        }
        return response.toString();
    }
    else {
        return null;
    }
}

来自清单的权限:

<uses-permission android:name="android.permission.INTERNET"></uses-permission>
<uses-permission android:name="android.permission.ACCESS_NETWORK_STATE"> </uses-permission>

登录

没有什么有趣的。

public boolean signIn(String _email, String _pass) throws IOException {
    String link = signInURL;
    String signInData = "email="+_email+"&password="+_pass;
    String response = sendPost(link, signInData);
    System.out.println(response);
    if(response.compareTo("Logged") == 0) {
        return true;
    }
    return false;
}

制作吐司

makeToast 也一样——没什么意思。

protected void makeToast(String mess) {
    Toast t = Toast.makeText(getApplicationContext(), mess, Toast.LENGTH_SHORT);
    t.setGravity(Gravity.CENTER, 0, 0);
    t.show();
}

【问题讨论】:

  • 您是否在清单文件中授予了此权限。
  • 是的,而且还有一个权限
  • 请把访问网络的代码贴出来
  • 请添加Requester.signIn()代码
  • Requester.signIn(email, password) 方法在哪里?和 makeToast()?

标签: android asynchronous android-asynctask httpurlconnection networkonmainthread


【解决方案1】:

一个问题是:

        String email = eField.getText().toString();
        String password = pField.getText().toString();

您不应该从非 UI 线程访问 UI,不确定是否使用 getText - 但将其设置为规则总是更好。您可以在 onPreExecute 中读取字段,也可以在 AsyncTask 的 onPostExecute 中显示 Toast。

否则您的代码看起来不错,您可能会附加完整的 stact 跟踪,而不仅仅是一行

【讨论】:

    【解决方案2】:
    --Check your doInBackground part i am 100% sure you show "Toast" in else part
        else {
                makeToast("Нет доступа к интернету."); <--
            }
    
    -You can't update UI stuff in doInBackground(). Hence, you can't display a Toast there. You 
     needto   move this to onPostExecute() or somewhere else. Possibly onProgressUpdate()
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2013-12-15
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2012-01-01
      • 2014-07-13
      相关资源
      最近更新 更多