i have problems with my http-headers.
I need to send a post-request with an empty body and the header "Content-Length:0". But this seems impossible, becauce i get this exception:
--org.apache.http.ProtocolException: Content-Length header already present--
But when i do not include the header, there is no Content-Length header in the request and therefore i get 400: Bad Request.
I build this in Python too and there it works fine, but i can not make it work in java. Can you help me, please?
Here is my Code:
HttpClient client = HttpClientBuilder.create().build();
HttpPost httpPost = new HttpPost(url);
httpPost.addHeader(header..);
httpPost.addHeader(another header);
httpPost.addHeader("Content-Type","application/xml");
httpPost.addHeader("Content-Length","0");
httpPost.addHeader(another header);
HttpResponse response = client.execute(httpPost);
System.out.println(response.getStatusLine().getStatusCode());
EDIT:
Solved the problem with the answer from #Beno Arakelyan.
I tried to send the Content-Length with http-request which built on apache http client. It works fine. Example:
private static final HttpRequest<?> HTTP_REQUEST =
HttpRequestBuilder.createGet(YOUR_URI)
.addDefaultHeader(HttpHeaders.CONTENT_LENGTH, "0")
.build();
public void test(){
System.out.println(HTTP_REQUEST.execute().getStatisCode()); // is 200
}
You don't need to calculate the content length, the client will handle that for you. Try removing the header and set a body instead, for example: httpPost.setEntity(new StringEntity("")).
This Link directs you to the example below
URL url = new URL("https://reqbin.com/echo/post/json");
HttpURLConnection http = (HttpURLConnection)url.openConnection();
http.setRequestMethod("POST");
http.setDoOutput(true);
http.setRequestProperty("Content-Type", "application/json");
String data = "{\"widget\": {\n \"window\": {\n \"title\": \"Sample Widget\",\n \"name\": \"sample_widget\",\n \"width\": 600,\n \"height\": 400\n },\n \"image\": { \n \"src\": \"images/test.png\",\n \"name\": \"sample_test\",\n \"hOffset\": 150,\n \"vOffset\": 150,\n \"alignment\": \"center\"\n },\n \"text\": {\n \"data\": \"Click Here\",\n \"size\": 36,\n \"style\": \"bold\",\n \"name\": \"sample_click\",\n \"alignment\": \"center\"\n }\n}} ";
byte[] out = data.getBytes(StandardCharsets.UTF_8);
OutputStream stream = http.getOutputStream();
stream.write(out);
System.out.println(http.getResponseCode() + " " + http.getResponseMessage());
http.disconnect();
Note: Content-Length will be added automatically.
Related
For example, you can extract the status code from a CloseableHTTPResponse using response.getStatusLine().getStatusCode().
Is there a similar way to get a specific header value (ie. Location, Date, etc.) from the response (in String format)?
You can do it using getFirstHeader("key").
Apache HttpClient example:
HttpClient client = HttpClientBuilder.create().build();
HttpGet request = new HttpGet("http://api.com");
HttpResponse response = client.execute(request);
//get header by 'key'
String headerName= response.getFirstHeader("headerName").getValue();
If you want to get all the headers, you can use getAllHeaders().
//get all headers
Header[] headers = response.getAllHeaders();
for (Header header : headers) {
System.out.println("Key : " + header.getName()
+ " ,Value : " + header.getValue());
}
I am trying to call an api. Whenever i include 'é' in the request body getting 400 bad request. When i remvove 'é' everything works fine. below is my code and response.
CloseableHttpClient httpClient = (CloseableHttpClient) getHttpClient();
HttpPost httpPost = getHttpPost("xxx");
StringEntity entity = new StringEntity(request.toString());
entity.setChunked(false);
httpPost.addHeader("content-type", "application/json");
httpPost.setEntity(entity);
System.out.println("contentlength = "+String.valueOf(entity.getContentLength()));
CloseableHttpResponse response = (CloseableHttpResponse) httpClient.execute(httpPost);
System.out.println("response = "
+ response);
StatusLine statusLine = response.getStatusLine();
System.out.println("statusLine = "
+ statusLine);
String responseEntity = EntityUtils.toString(response.getEntity());
System.out.println("responseEntity = "
+ responseEntity);
Response :
contentlength = 964 response = HttpResponseProxy{HTTP/1.1 400 Bad
Request [Content-Length: 0,Chunked: false]} statusLine = HTTP/1.1 400
Bad Request responseEntity =
StringEntity entity = new StringEntity(request.toString(),"UTF-8");
this solved the issue.
Set the content-type to:
"application/json;charset=UTF-8"
when sending the post request in the application you are using.
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();
}
I have to pass xml in a request, but I cannot figure out how can I perform it :/. Can you please help me?
I've already stored and prepared the xml.
The request sample:
POST http://..... HTTP/1.0
Content-type: text/xml
and xml
Thanks in advance
What is the source and destination of your xml?
If your source is say a file, and your destination is say a servlet, you can use curl http://en.wikipedia.org/wiki/CURL to send the xml and a servlet to receive it.
The servlet 3.0 spec has new features for this kind of stuff so that should make it easy.
OR
Are you trying to send a post from your java application?
John : )
Use HttpClient
Following is the code I use to post xml to a server.
String payload = <XML String>
HttpPost post = new HttpPost("http://" + ip + ":" + port);
LOGGER.info("WebService Call for " + ip + ":" + port);
try {
StringEntity entity = new StringEntity(payload);
post.setEntity(entity);
HttpResponse response = httpClient.execute(post);
HttpEntity resEntity = response.getEntity();
EntityUtils.consume(resEntity);
} finally {
post.releaseConnection();
}
I am struggling with creating a plain text file on a server via HTTP PUT. I am using apache commons httpClient. My credentials are working but there is no body content in my request. What must I do to create the file like this? It works as intended when I try via hurl.it (ie setting my credentials, and setting a body). What I would like is the string "hej" to show in the file body. After getting this to work I intend to use a JSONString. The following code generates an empty file on the server (204 response):
HttpClient httpClient = new DefaultHttpClient();
String encoding = http_username + ":" + http_password;
encoding = Base64.encodeBase64String(encoding.getBytes());
HttpPut httpput = new HttpPut(http_path);
HttpEntity content=null;
try{
content = new StringEntity("hej");
}
catch(UnsupportedEncodingException e){
logger.error("Failed to Encode result");
}
logger.info("executing request " + httpput.getRequestLine());
try {
httpput.setHeader("Authorization", "Basic " + encoding);
//httpput.setHeader("Content-Type", "application/json; charset=utf-8");
httpput.setEntity(content);
HttpResponse response = httpClient.execute(httpput);
Header[] allHeaders = response.getAllHeaders();
for (Header h : allHeaders) {
logger.info(h.getName() + ": " + h.getValue());
}
} catch (Exception e) {
logger.error(e.getMessage());
}
I have tried both setting a content type and not doing it, no difference. What basic thing am I doing wrong?
Turns out that Base64.encodeBase64String appends a newline character at the end of the string, which throws everything off!
String encoding = http_username + ":" + http_password;
encoding = Base64.encodeBase64String(encoding.getBytes());
encoding= encoding.replace("\r\n", ""); //This fixes everything
Wow, that just took me a couple of days to figure out!