【问题标题】:Problems with setting Authorization in request headers from Java在 Java 的请求标头中设置授权的问题
【发布时间】:2018-01-31 20:28:47
【问题描述】:

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

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

希望尽快听到。谢谢。

【问题讨论】:

  • 你怎么知道 header 没有设置
  • “我无法设置任何数据”。以什么方式?
  • 替换这个 myURLConnection.setRequestProperty("Authorization", "basicAuth");与 myURLConnection.setRequestProperty("Authorization", basicAuth);
  • 嗨,Ivar,我发现标题中没有占用数据的唯一实例是我使用“授权”时。我什至尝试了“TEST”,然后就进去了。

标签: java apache httpurlconnection urlconnection


【解决方案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();
}

【讨论】:

    【解决方案2】:

    声明

    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

    这并不意味着没有设置标题。

    【讨论】:

      【解决方案3】:

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

      myURLConnection.setRequestProperty("Authorization", basicAuth);
      

      或者试试这个:

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

      【讨论】:

      • 嗨 sForSujit,对不起我的错误。但这也没有用。
      • 为什么不用 URLConnection 而不是 HttpURLConnection
      猜你喜欢
      • 1970-01-01
      • 2018-04-26
      • 1970-01-01
      • 1970-01-01
      • 2021-07-16
      • 2017-12-17
      • 2017-04-17
      • 2013-01-21
      • 2019-05-15
      相关资源
      最近更新 更多