I am using rest template for creating HTTP post request . But request contain by default added Accept-char header with huge Content . Please suggest how to exclude addition of that header. Below is the code i am using:
HttpHeader header= new HttpHeader();
RestTemplate template = new RestTemplate();
header.setContentType("application/xml");
String body=" content of body ";
HttpEntity<string> request=new HttpEntity<string> (body,header);
template.postForObject(URL,request,String.class);
This should remove 'Accept-Charset' header:
StringHttpMessageConverter stringHttpMessageConverter = new StringHttpMessageConverter(StandardCharsets.UTF_8);
stringHttpMessageConverter.setWriteAcceptCharset(false);
restTemplate.getMessageConverters().add(0, stringHttpMessageConverter);
Related
How can I send the request to my api
My request body only contains a value and no key. How can I create my request body without error.
FormBody.Builder requestBody = new FormBody.Builder();
requestBody.add(null, "abc");
Request request = new Request.Builder()
.url(HttpUrl.get(uri))
.post(requestBody.build())
.header("id", "12345")
.build();
Thank you.
The server I am sending a POST request to requires extra parameters in the Content-Disposition field that are easily added in C# code, but I am struggling to replicate this functionality in Java.
The working C# code:
using (var content = new MultipartFormDataContent()) {
var fileContent = new ByteArrayContent(System.IO.File.ReadAllBytes("filepath"));
fileContent.Headers.ContentDisposition = new ContentDispositionHeaderValue("form-data")
{
Name = "file",
FileName = "file.zip.encrypted",
};
fileContent.Headers.ContentDisposition.Parameters.Add(new NameValueHeaderValue("Type", "CSV"));
fileContent.Headers.ContentDisposition.Parameters.Add(new NameValueHeaderValue("Token", jwt));
content.Add(fileContent);
var requestUri = "url";
var result = client.PostAsync(requestUri, content).Result;
When I print the above request headers the Content-Disposition header looks like:
Content-Disposition: form-data; name=file; filename=file.zip.encrypted; Type=CSV; Token=jwt
Attempting to replicate this POST request in Java Apache Http:
File file = new File("filepath");
String headerValue = "form-data; name=file; filename=\"file.zip.encrypted\"; Type=\"CSV\"; Token=\""+jwtToken+"\"";
try (CloseableHttpClient client2 = HttpClients.createDefault()) {
HttpPost post2 = new HttpPost(url);
HttpEntity entity = MultipartEntityBuilder.create().addPart("file", new FileBody(file)).build();
post2.setHeader("Content-Disposition", headerValue);
post2.setEntity(entity);
try (CloseableHttpResponse response2 = client2.execute(post2)) {
System.out.println(response2.toString());
}
}
However, when I print the Headers in this request, only the name and filename fields are captured, and not the other parameters required in the Content-Disposition header. This is leading to Internal Server Error responses, as the Header does not contain the required parameters. (tried with and without the added quotes around field values)
Content-Disposition: form-data; name="file"; filename="file.zip.encrypted"
Any help getting the C# POST request behavior replicated in Java would be greatly appreciated, thanks!
I'm trying to generate a token by passing Base64 encoded value in the form of Header, but getting "java.util.zip.ZipException: incorrect header check"
RestAssured.baseURI = uri;
RequestSpecification request = RestAssured.given();
request = request.header("Authorization", "Basic "+encodedString);
Response response = request.when().post();
Showing "java.util.zip.ZipException: incorrect header check" exception.
try
RestAssured.config = config().decoderConfig(decoderConfig().useNoWrapForInflatedStreams(true));
Good day,
I write server code (java, spring) that serves GET request.
The response should be in multipart-form format and should include 2 parts: string (json object) and file data.
The code is:
FileSystemResource resource = new FileSystemResource(targetFile);
String info = getInfo(targetFile);
MultiValueMap<String, Object> form = new LinkedMultiValueMap<String, Object>();
form.add("info", info);
form.add("file", resource);
MediaType multiPart =
MediaType.parseMediaType(MediaType.MULTIPART_FORM_DATA_VALUE);
ResponseEntity <MultiValueMap<String, Object>> responseEntity =
ResponseEntity.ok().contentType(multiPart).body(form);
return responseEntity;
The code works OK, but I didn't find a way to define content type of parts.
For first part it should be application/json, and for second part it depends on file type.
How to define this?
Did you try this?
HttpHeaders headers = new HttpHeaders();
headers.setContentDisposition(ContentDisposition.builder("inline; filename=\"" + resource.getFilename() + "\"").build());
headers.setContentType(MediaType.APPLICATION_JSON);
headers.setContentLength(resource.contentLength());
return new ResponseEntity<>(resource, headers, HttpStatus.OK);
Best Regards.
The goal is to send an email with inline image. Everything is working well, except the image is not appearing in the email.
My approach is based on this Jersey-example of Mailgun's User Guide.
public static ClientResponse SendInlineImage() {
Client client = Client.create();
client.addFilter(new HTTPBasicAuthFilter("api",
"YOUR_API_KEY"));
WebResource webResource =
client.resource("https://api.mailgun.net/v3/YOUR_DOMAIN_NAME" +
"/messages");
FormDataMultiPart form = new FormDataMultiPart();
form.field("from", "Excited User <YOU#YOUR_DOMAIN_NAME>");
form.field("to", "baz#example.com");
form.field("subject", "Hello");
form.field("text", "Testing some Mailgun awesomness!");
form.field("html", "<html>Inline image here: <img src=\"cid:test.jpg\"></html>");
File jpgFile = new File("files/test.jpg");
form.bodyPart(new FileDataBodyPart("inline",jpgFile,
MediaType.APPLICATION_OCTET_STREAM_TYPE));
return webResource.type(MediaType.MULTIPART_FORM_DATA_TYPE).
post(ClientResponse.class, form);
}
However, I need to use Spring's RestTemplate.
This is what I've got so far:
RestTemplate template = new RestTemplate();
MultiValueMap<String, Object> map = new LinkedMultiValueMap<>();
// ... put all strings in map (from, to, subject, html)
HttpHeaders headers = new HttpHeaders();
// ... put auth credentials on header, and content type multipart/form-data
template.exchange(MAILGUN_API_BASE_URL + "/messages", HttpMethod.POST,
new HttpEntity<>(map, headers), String.class);
The remaining part is to put the *.png file into the map. Not sure how to do that. Have tried reading all its bytes via ServletContextResource#getInputStream, but without success: Image is not appearing in the resulting e-mail.
Am I missing something here?
This turned out to be a case where everything was set up correctly, but only a small detail prevented it from working.
map.add("inline", new ServletContextResource(this.servletContext,
"/resources/images/email-banner.png"));
For Mailgun you need to use the map-key "inline". Also, the ServletContextResource has a method getFilename(), which is used to resolve against the image tag. Thus, the image tag should have the following content id:
<img src="cid:email-banner.png"/>