0

我遇到了使用 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");
    }

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

谢谢,

4

2 回答 2

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

我对NetworkOnMainThread异常有疑问。

看看如何修复 android.os.NetworkOnMainThreadException?

Android AsyncTask是最好的解决方案。

更新:

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

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

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

于 2013-01-04T10:41:37.953 回答
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);

如果您不知道如何使用异步任务,这里有一些教程供您参考:

教程 1
教程 2

这是官方文档

于 2013-01-04T10:49:24.713 回答