Java 如何在Android中发送HTTP基本身份验证标头?

Java 如何在Android中发送HTTP基本身份验证标头?,java,android,json,httpclient,http-authentication,Java,Android,Json,Httpclient,Http Authentication,我不知道如何发送HTTP验证头 我有以下HttpClient来获取请求,但不确定如何发送请求 public class RestClient extends AsyncTask<String, Void, JSONObject> { private String convertStreamToString(InputStream is) { /* * To convert the InputStream to Stri

我不知道如何发送HTTP验证头

我有以下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) {

        }
    }
public类RestClient扩展异步任务{
私有字符串convertStreamToString(InputStream为){
/*
*要将InputStream转换为字符串,我们使用
*方法。我们迭代直到
*BufferedReader返回null,这意味着没有更多的数据要存储
*读取。每行都将附加到StringBuilder并作为
*绳子。
*/
BufferedReader reader=新的BufferedReader(新的InputStreamReader(is));
StringBuilder sb=新的StringBuilder();
字符串行=null;
试一试{
而((line=reader.readLine())!=null){
sb.追加(第+行“\n”);
}
}捕获(IOE异常){
e、 printStackTrace();
}最后{
试一试{
is.close();
}捕获(IOE异常){
e、 printStackTrace();
}
}
使某人返回字符串();
}
/*
*这是一个将连接到给定rest服务的测试函数
*并用标签“Praeda”打印它对Android日志的响应。
*/
公共JSONObject连接(字符串url){
HttpClient HttpClient=新的DefaultHttpClient();
//准备一个请求对象
HttpGet HttpGet=新的HttpGet(url);
//执行请求
HttpResponse响应;
试一试{
response=httpclient.execute(httpget);
//检查响应状态
Log.i(“Praeda”,response.getStatusLine().toString());
//获取响应实体
HttpEntity=response.getEntity();
如果(实体!=null){
//一个简单的JSON响应读取
InputStream instream=entity.getContent();
字符串结果=convertStreamToString(流内);
//一个简单的JSONObject创建
JSONObject json=新的JSONObject(结果);
//关闭输入流将触发连接释放
流内关闭();
返回json;
}
}捕获(客户端协议例外e){
e、 printStackTrace();
}捕获(IOE异常){
e、 printStackTrace();
}捕获(JSONException e){
e、 printStackTrace();
}
返回null;
}
@凌驾
受保护的JSONObject doInBackground(字符串…URL){
返回连接(URL[0]);
}
@凌驾
受保护的void onPostExecute(JSONObject json){
}
}

这在HttpClient及其应用程序中有介绍。

也许HttpClient的文档可以提供帮助:

因为Android编译HttpClient 4.0.x而不是3.x,下面的代码片段供您参考

    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);

仅供参考,您的链接是针对HttpClient 3.x的,Android内置了HttpClient 4.x。文档中的某些方法在Android平台上不存在。