在Java

时间:2017-08-23 09:56:39

标签: java apache httpurlconnection urlconnection

我遇到一个问题,我无法设置“授权”标题。 我可以设置其余的标题,但是当我使用特定的键时,我无法设置任何数据。请帮忙。

URL myURL = new URL(url);
HttpURLConnection myURLConnection = (HttpURLConnection)myURL.openConnection();
String basicAuth = "Bearer 6f6b06fe-131e-314b-9ef8-42f2cbdcfc18";
myURLConnection.setRequestMethod("GET");
myURLConnection.setRequestProperty("Accept-Language", "en-US,en;q=0.5");
myURLConnection.setRequestProperty("Content-Type", "application/x-www-form-urlencoded");
myURLConnection.setRequestProperty("Content-Language", "en-US");
myURLConnection.setRequestProperty("Authorization", "basicAuth");
myURLConnection.setUseCaches(false);
myURLConnection.setDoInput(true);
myURLConnection.setDoOutput(true);
System.out.println(myURLConnection.getRequestProperties());

希望尽快听到。谢谢。

3 个答案:

答案 0 :(得分:1)

声明

QMLProxyModel

未列出所有标题。

通过查看myURLConnection.getRequestProperties() 的来源,您注意HttpURLConnectionAuthorization排除的标题的一部分。

http://hg.openjdk.java.net/jdk8/jdk8/jdk/file/484e16c0a040/src/share/classes/sun/net/www/protocol/http/HttpURLConnection.java

这并不意味着未设置标头。

答案 1 :(得分:0)

我认为你在那里犯了一个小错误,关键授权的价值不能是“basicAuth”。所以请用以下代码替换代码:

myURLConnection.setRequestProperty("Authorization", basicAuth);

或试试这个:

 String basicAuth = "Bearer 6f6b06fe-131e-314b-9ef8-42f2cbdcfc18";
 String encodedAuth= Base64.encode(basicAuth.getBytes());
 myURLConnection.setRequestProperty("Authorization", encodedAuth);

答案 2 :(得分:-1)

尝试使用以下代码:

public void sendPost(String URL, String jsonData, String authUrl) throws Exception {
post = new HttpPost(URL);
// add header
post.setHeader("Authorization", accessToken);
post.setHeader("User-Agent", USER_AGENT);
if (!jsonData.isEmpty()) {
post.setEntity(new StringEntity(jsonData, ContentType.create("application/json")));
}
client = HttpClientBuilder.create().build();
response = client.execute(post);
outputFile = new File("path of file");
fos = new FileOutputStream(outputFile);
headers = response.getAllHeaders();
bw = new BufferedWriter(new OutputStreamWriter(fos));
for (Header header : headers) {
bw.write(header.getName() + ": " + header.getValue() + "\n");
}

bw.write("Response Code : " + response.getStatusLine());
bw.close();
}