尝试执行HTTP Post时出现NetworkOnMainThread错误

时间:2013-07-26 11:33:29

标签: java android http-post networkonmainthread

您好我正在尝试向基于PHP的服务器发送简单的HTTP帖子,该服务器接受POST数据$ _POST ['username']。

public void sendMessage(View view){

    String result = "";

    Intent intent = new Intent(this, DisplayMessageActivity.class);
    EditText editText = (EditText) findViewById(R.id.edit_message);
    String message = editText.getText().toString();
    intent.putExtra(EXTRA_MESSAGE, message);

    Toast.makeText(
            getApplicationContext(),
            "Attempting to open second activity",
            Toast.LENGTH_LONG
    ).show();

    ArrayList<NameValuePair> nameValuePairs = new ArrayList<NameValuePair>();
    nameValuePairs.add(new BasicNameValuePair("username","ghost"));

    InputStream is = null;

    // ATTEMPT HTTP POST
    try{
        HttpClient httpclient = new DefaultHttpClient();
        HttpPost httppost = new HttpPost("http://example.com/getuserbyuname");
            httppost.setEntity(new UrlEncodedFormEntity(nameValuePairs));
            HttpResponse response = httpclient.execute(httppost);
            HttpEntity entity = response.getEntity();
            is = entity.getContent();
    }catch(Exception e){
            Log.e("log_tag", "Error in http connection (Reason: " + e.toString() + " )");
    }

然后,服务器将返回JSON格式的消息,如下所示:

{"response":"404"}

我遇到了android.os.NetworkOnMainThread的问题。我知道这是因为我的例程是尝试从主UI线程中执行与网络相关的操作。

我试过这个:

public class AccountConnector extends AsyncTask <String, Integer, Long>{

@Override
protected Long doInBackground(String... params)
{
    ArrayList<NameValuePair> nameValuePairs = new ArrayList<NameValuePair>();
    nameValuePairs.add(new BasicNameValuePair("username","bond"));

    InputStream is = null;

    // ATTEMPT HTTP POST
    try{
        HttpClient httpclient = new DefaultHttpClient();
        HttpPost httppost = new HttpPost("http://example.com/getuserbyuname");
            httppost.setEntity(new UrlEncodedFormEntity(nameValuePairs));
            HttpResponse response = httpclient.execute(httppost);
            HttpEntity entity = response.getEntity();
            is = entity.getContent();
    }catch(Exception e){
            Log.e("log_tag", "Error in http connection (Reason: " + e.toString() + " )");
    }
    return null;
}

...其余代码被省略......

有人能指出我正确的方向吗?

2 个答案:

答案 0 :(得分:0)

添加此..

StrictMode.ThreadPolicy policy = new StrictMode.ThreadPolicy.Builder()
             .permitAll().build();
StrictMode.setThreadPolicy(policy);

把它放在清单文件中

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

答案 1 :(得分:0)

解决此问题的正确方法是使用Android AsyncTask进行网络访问。

处理此问题的懒惰方式是检查:

StrictMode.ThreadPolicy policy = new StrictMode.ThreadPolicy.Builder().permitAll().build();
StrictMode.setThreadPolicy(policy);