【问题标题】:How can I send HTTP Basic Authentication headers in Android?如何在 Android 中发送 HTTP 基本身份验证标头?
【发布时间】:2010-11-22 22:44:08
【问题描述】:

我不确定如何发送 HTTP Auth 标头。

我有以下 HttpClient 来获取请求,但不确定如何发送请求?

public class RestClient extends AsyncTask<String, Void, JSONObject> {
        private String convertStreamToString(InputStream is) {
            /*
             * To convert the InputStream to String we use the
             * BufferedReader.readLine() method. We iterate until the
             * BufferedReader return null which means there's no more data to
             * read. Each line will appended to a StringBuilder and returned as
             * String.
             */
            BufferedReader reader = new BufferedReader(new InputStreamReader(is));
            StringBuilder sb = new StringBuilder();

            String line = null;
            try {
                while ((line = reader.readLine()) != null) {
                    sb.append(line + "\n");
                }
            } catch (IOException e) {
                e.printStackTrace();
            } finally {
                try {
                    is.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }

            return sb.toString();
        }

        /*
         * This is a test function which will connects to a given rest service
         * and prints it's response to Android Log with labels "Praeda".
         */
        public JSONObject connect(String url) {
            HttpClient httpclient = new DefaultHttpClient();

            // Prepare a request object
            HttpGet httpget = new HttpGet(url);

            // Execute the request
            HttpResponse response;
            try {
                response = httpclient.execute(httpget);
                // Examine the response status
                Log.i("Praeda", response.getStatusLine().toString());

                // Get hold of the response entity
                HttpEntity entity = response.getEntity();

                if (entity != null) {

                    // A Simple JSON Response Read
                    InputStream instream = entity.getContent();
                    String result = convertStreamToString(instream);

                    // A Simple JSONObject Creation
                    JSONObject json = new JSONObject(result);

                    // Closing the input stream will trigger connection release
                    instream.close();

                    return json;
                }

            } catch (ClientProtocolException e) {
                e.printStackTrace();
            } catch (IOException e) {
                e.printStackTrace();
            } catch (JSONException e) {
                e.printStackTrace();
            }

            return null;
        }

        @Override
        protected JSONObject doInBackground(String... urls) {
            return connect(urls[0]);
        }

        @Override
        protected void onPostExecute(JSONObject json) {

        }
    }

【问题讨论】:

    标签: java android json httpclient http-authentication


    【解决方案1】:

    这在 HttpClient documentation 和他们的 sample code 中都有介绍。

    【讨论】:

    • 文档中的某些方法在android平台上不存在。
    【解决方案2】:

    也许HttpClient的文档可以帮助:link

    【讨论】:

    • 仅供参考,您的链接适用于 HttpClient 3.x,Android 内置了 HttpClient 4.x。
    【解决方案3】:

    由于Android编译的是HttpClient 4.0.x而不是3.x,下面的sn-p供大家参考。

        if (authState.getAuthScheme() == null) {
            AuthScope authScope = new Au    HttpRequestInterceptor preemptiveAuth = new HttpRequestInterceptor() {
        public void process(final HttpRequest request, final HttpContext context) throws HttpException, IOException {
            AuthState authState = (AuthState) context.getAttribute(ClientContext.TARGET_AUTH_STATE);
            CredentialsProvider credsProvider = (CredentialsProvider) context.getAttribute(
                    ClientContext.CREDS_PROVIDER);
            HttpHost targetHost = (HttpHost) context.getAttribute(ExecutionContext.HTTP_TARGET_HOST);thScope(targetHost.getHostName(), targetHost.getPort());
            Credentials creds = credsProvider.getCredentials(authScope);
            if (creds != null) {
                authState.setAuthScheme(new BasicScheme());
                authState.setCredentials(creds);
            }
        }
    }    
    };
    DefaultHttpClient httpclient = new DefaultHttpClient();
    httpclient.addRequestInterceptor(preemptiveAuth, 0);
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2014-01-30
      • 2015-05-13
      • 1970-01-01
      • 2019-08-08
      • 1970-01-01
      • 1970-01-01
      • 2013-08-18
      • 2015-03-13
      相关资源
      最近更新 更多