簡體   English   中英

在Java請求標頭中設置授權問題

[英]Problems with setting Authorization in request headers from Java

我遇到無法設置“授權”標題的問題。 我可以設置其余的標題,但是當我使用特定的鍵時,我無法設置任何數據。 請幫忙。

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

希望能盡快聽到。 謝謝。

該聲明

myURLConnection.getRequestProperties()

沒有列出所有標題。

通過查看HttpURLConnection的來源,您會注意到AuthorizationHttpURLConnection#getRequestProperties排除的標頭的一部分。

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

這並不意味着沒有設置標題。

我認為您在此處犯了一個小錯誤,密鑰授權的值一定不能為“ basicAuth”。 因此,請將代碼替換為:

myURLConnection.setRequestProperty("Authorization", basicAuth);

或者試試這個:

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

嘗試以下代碼:

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

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM