简体   繁体   中英

Problems with setting Authorization in request headers from Java

I am facing a problem where I am not able to set the "Authorization" Header. I am Able to set the rest of the headers but when I am using the particular Key I am not able to set any data. Please help.

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

Hoping to hear soon. Thank you.

The statement

myURLConnection.getRequestProperties()

does not list all headers.

By looking at the source of HttpURLConnection you notice Authorization is part of the headers excluded by HttpURLConnection#getRequestProperties .

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

This does not mean the header isn't set.

I think You made a little mistake there, The value for the key Authorization must not be "basicAuth". So please replace the code with :

myURLConnection.setRequestProperty("Authorization", basicAuth);

Or try this :

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

Try with following code:

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM