java 如何在 httpRequest 中设置标头身份验证?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/32261010/
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-11-02 19:54:37 来源:igfitidea点击:
How to set header Authentication in httpRequest?
提问by
How to set header Authentication in httpRequest?
如何在 httpRequest 中设置标头身份验证?
I tried with this, but It didn't work well.
我试过这个,但效果不佳。
connection.setRequestMethod("GET");
connection.setRequestProperty ("Authorization", accesToken);
connection.setRequestProperty("Accept", "application/json");
采纳答案by Peter Peng
Here is what I do for HTTP request with Basic Authentication:
这是我使用基本身份验证对 HTTP 请求执行的操作:
String pageUrl ="http://......";
String username = "yourUsername";
String password = "yourPassword";
HttpParams httpParams = new BasicHttpParams();
int timeoutConnection = 10000;
HttpConnectionParams.setConnectionTimeout(httpParams, timeoutConnection);
int timeoutSocket = 10000;
HttpConnectionParams.setSoTimeout(httpParams, timeoutSocket);
HttpClient httpClient = new DefaultHttpClient(httpParams);
HttpGet httpGet = new HttpGet(pageUrl);
String credential = Base64.encodeToString( (username+":"+password).getBytes("UTF-8"), Base64.DEFAULT);
httpGet.setHeader("Authorization", "Basic " + credential.substring(0, credential.length()-1));
httpGet.setHeader("Accept", "application/json");
httpGet.setHeader("Connection", "close");
HttpResponse httpResponse = httpClient.execute(httpGet);
StatusLine statusLine = httpResponse.getStatusLine();
if(statusLine.getStatusCode() == HttpStatus.SC_OK)
{
ByteArrayOutputStream outputStream = new ByteArrayOutputStream();
httpResponse.getEntity().writeTo(outputStream);
String responseString = outputStream.toString();
System.out.println(responseString);
...... //processding operations
}