版本4.0.3的Android Http请求问题

时间:2013-01-04 10:38:19

标签: android http httpclient

我使用HttpClient遇到了http请求,该版本在2.2或2.3.X版本中运行良好。但当我尝试从版本4.0.3的Android平板电脑发送该请求时,它给了我 401错误

这是我实施的代码。

HttpClient client = new DefaultHttpClient();
    HttpConnectionParams.setConnectionTimeout(client.getParams(), 10000); //Timeout Limit
    HttpResponse response;
    JSONObject json = new JSONObject();
    try{
        HttpPost post = new HttpPost("MYURL");
        json.put("username", username);
        json.put("password", password);
        StringEntity se = new StringEntity( json.toString());  
        se.setContentType(new BasicHeader(HTTP.CONTENT_TYPE, "application/json"));
        post.setEntity(se);
        response = client.execute(post);
        /*Checking response */
        statusCode = response.getStatusLine().getStatusCode();
        System.out.println("Status Code=>" + statusCode);
        if (statusCode == 200) {
            result = EntityUtils.toString(response.getEntity());
            Log.v("Login Response", "" + result);
        } else {
            response = null;
        }
    }
    catch(Exception e){

        e.printStackTrace();
        //createDialog("Error", "Cannot Estabilish Connection");
    }

帮助我用最好的建议解决这个问题。

谢谢,

2 个答案:

答案 0 :(得分:2)

I'm getting stuck with http request using HttpClient that is working fine with 2.2 or 2.3.X versions.

我怀疑NetworkOnMainThread例外。

查看How to fix android.os.NetworkOnMainThreadException?

Android AsyncTask是最佳解决方案。

<强>更新

此外,您收到401错误状态代码。

401 means "Unauthorized", so there must be something with your credentials.

在请求Web服务之前,请检查凭据。

答案 1 :(得分:1)

您正在主线程上运行网络操作。使用异步任务在后台线程中运行网络操作。这就是你获得android.os.NetworkOnMainThreadException的原因。

在这样的异步任务中执行此操作:

class MyTask extends AsyncTask<String, Void, RSSFeed> {

    protected void onPreExecute() {
        //show a progress dialog to the user or something
    }

    protected void doInBackground(String... urls) {
        //do network stuff
    }

    protected void onPostExecute() {
        //do something post execution here and dismiss the progress dialog
    }
 }

 new MyTask().execute(null);

如果您不知道如何使用异步任务,以下是一些教程:

Tutorial 1
Tutorial 2

这是official docs