Java 如何使用 HTTPClient 设置 HTTP 请求头“身份验证”?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/3983604/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-14 07:54:55  来源:igfitidea点击:

How to set HTTP Request Header "authentication" using HTTPClient?

javaauthorizationhttpclientbasic-authentication

提问by user855

I want to set the HTTP Request header "Authorization" when sending a POST request to a server. How do I do it in Java? Does HttpClient have any support for it?

我想在向服务器发送 POST 请求时设置 HTTP 请求标头“授权”。我如何在 Java 中做到这一点?HttpClient 是否支持它?

http://www.w3.org/Protocols/HTTP/HTRQ_Headers.html#z9

http://www.w3.org/Protocols/HTTP/HTRQ_Headers.html#z9

The server requires me to set some specific value for the authorization field: of the form ID:signature which they will then use to authenticate the request.

服务器要求我为授权字段设置一些特定的值:表单 ID:signature 然后他们将使用它来验证请求。

Thanks Ajay

谢谢阿杰

回答by Fahad

Below is the example for setting request headers

下面是设置请求头的例子

    HttpPost post = new HttpPost("someurl");

    post.addHeader(key1, value1));
    post.addHeader(key2, value2));

回答by Francisco Corrales Morales

Here is the code for a Basic Access Authentication:

这是基本访问身份验证的代码:

HttpPost request = new HttpPost("http://example.com/auth");
request.addHeader("Authorization", "Basic ThisIsJustAnExample");

And then just an example of how to execute it:

然后只是一个如何执行它的例子:

HttpParams httpParams = new BasicHttpParams();
HttpProtocolParams.setVersion(httpParams, HttpVersion.HTTP_1_1);
HttpConnectionParams.setConnectionTimeout(httpParams, 3000);
HttpClient httpclient = null;
httpclient = new DefaultHttpClient(httpParams);

HttpResponse response = httpclient.execute(request);

Log.d("Log------------", "Status Code: " + response.getStatusLine().getStatusCode());

回答by Nick

This question is "answered" here: Http Basic Authentication in Java using HttpClient?

这个问题在这里“回答”: Http Basic Authentication in Java using HttpClient?

There are many ways to do this. It was frustrating for me to try to find the answer. I found that the best was the Apache docs for HttpClient. Note: answers will change over time as the libraries used will have deprecated methods. http://hc.apache.org/httpcomponents-client-4.5.x/tutorial/html/authentication.html

有很多方法可以做到这一点。试图找到答案让我很沮丧。我发现最好的是 HttpClient 的 Apache 文档。注意:答案会随着时间的推移而改变,因为所使用的库将具有不推荐使用的方法。 http://hc.apache.org/httpcomponents-client-4.5.x/tutorial/html/authentication.html