HttpPost not sending params once over a certain size - java

Here is the code:
HttpClient client = new HttpClient();
PostMethod method = new PostMethod(SERVER_URL);
NameValuePair[] data = {
new NameValuePair("html", html)
};
method.setRequestBody(data);
Once the value for the html var goes over a certain size all params become null for the receiving URL. Any ideas why?

This doesn't sound like a fault on the client side. I suspect that you may be hitting a server-side limit; e.g. a request-size limit specified in the web container configuration ... or a front-end.

Related

How to send list parameter with HTTPDELETE as RequestBody in java

Hi i have written a rest service to delete multiple files and i am trying to access the rest service.
My input to rest service will be List values which will be id of files that needs to be deleted.
For that i have written the below code
List<Long> ids=new ArrayList<Long>();
ids.add(4l);
ids.add(5l);
boolean status = false;
String jsonResponse = null;
DefaultHttpClient httpClient = null;
HttpResponse response = null;
try {
httpClient = new DefaultHttpClient();
StringBuilder url = new StringBuilder("http://localhost:8080/api/files");
URIBuilder builder = new URIBuilder();
URI uri = builder.build();
HttpDelete deleteRequest = new HttpDelete(uri);
//how to set list as Requestbody and send
response = httpClient.execute(deleteRequest);
}
Here i dont know how to set List as entity in request body and send. Can someone help me on this
A HTTP DELETE request should delete the resource identified by the URI. The body is not relevant. To delete a single resource:
DELETE /api/files/123
If you want to delete more than one file in a single request, model a collection of files as a resource. This could be done by listing more than one ID in the URL:
GET /api/files/123,456,789
This could return a JSON array with the details of the three files.
To delete these three files, execute a DELETE request agains the same URL:
DELETE /api/files/123,456,789

Mailgun API: Sending Inline Image with Spring's RestTemplate

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"/>

PUT Method: Not able to send "fileName" form Data using Jersey API using java?

following is the code I have written to PUT a image to a jersey server.
byte[] img = image(file);// coverts file into byte strea
FormDataMultiPart form = new FormDataMultiPart();
form.field("fileName", file);
FormDataBodyPart fdp = new FormDataBodyPart("fileUpload",
new ByteArrayInputStream(img),
MediaType.APPLICATION_OCTET_STREAM_TYPE);
form.bodyPart(fdp);
ClientResponse rs = wr.type(MediaType.APPLICATION_FORM_URLENCODED).put(
ClientResponse.class, form);
When I am running the code, i am able to send the byte stream to the server, but its returning error that it is not able to find the filename i am providing in form.field, so returning a 400 bad request error?
i am not able to understand what i am missing here?
I was able to fix the my problem. I was not adding multipart. This link helped me
Following is what i did to replace the body-part definition
FormDataBodyPart f = new FormDataBodyPart(FormDataContentDisposition
.name("fileUpload").fileName(file).build(),
new ByteArrayInputStream(img),
MediaType.APPLICATION_OCTET_STREAM_TYPE);
MultiPart multiPart = new FormDataMultiPart().bodyPart(f);
ClientResponse rs = wr.type(MediaType.MULTIPART_FORM_DATA).put(
ClientResponse.class, multiPart);

SOAP result null?

I have problem with my soap client. I have generate client part from wsdl using apache cxf.
I'm using Netbeans IDE and Maven. I also created HeaderHandler where I print soap response and it seems to be valid. But when I call web service method from my client a always get null value without any exception.
Any idea?
Thanks.
Update:
link to wsdl http://carecoprod.blueway.fr:8180/engine53/52/WSDL?name=AAA00_WsB2B&version=1&type=EAII
Client code:
{
AAA00WsB2B ss = new AAA00WsB2B(wsdlURL, SERVICE_NAME);
HeaderHandlerResolver h = new HeaderHandlerResolver();
ss.setHandlerResolver(h);
AAA00WsB2BPortType port = ss.getAAA00WsB2BPort();
System.out.println("Invoking aaa00WsB2B...");
AAA00WsB2BIN input = new AAA00WsB2BIN();
VarAAA v = new VarAAA();
v.setLogin("*******");
v.setImmat("*******");
v.setTypeReq("******");
v.setMdp("*******");
input.setVarAAA(v);
AAA00WsB2BOUT _aaa00WsB2B__return = new ObjectFactory().createAAA00WsB2BOUT();
_aaa00WsB2B__return = port.aaa00WsB2B(input);
System.out.println("aaa00WsB2B.result="+_aaa00WsB2B__return.getVarAAARetourWs().getCO2());
}

EntityUtils toString takes too long on big responses

The following code :
//
// Define HTTP Post and content
//
HttpPost httppost = new HttpPost(url);
ByteArrayEntity be = new ByteArrayEntity(strPostData.getBytes("UTF-8"));
httppost.setEntity(be);
//
// Define HTTP Client
//
HttpClient httpclient = new DefaultHttpClient();
HttpParams httpParameters = httpclient.getParams();
HttpConnectionParams.setConnectionTimeout(httpParameters, 10 * 1000);
//
// Sets the default socket timeout
// in milliseconds which is the timeout for waiting for data.
//
int timeoutSocket = 10000;
HttpConnectionParams.setSoTimeout(httpParameters, timeoutSocket);
HttpResponse response = httpclient.execute(httppost);
//
// This line takes too long on big responses
//
String content = EntityUtils.toString(response.getEntity());
The last line (EntityUtils.toString) takes too long when my response contains a large amount of Bytes.
I'm using HTTP Post to retrieve PDF files (up to 500 Kb) and it may take 1 or 2 seconds on each request, which is too much.
EDIT For Information : The PDF file is base 64 encoded and wrapped into XML Tag (the string is parsed after reception).
Is there any way to get my String response a faster way ?
EDIT 2 : in order to know how much time took my EntityUtils.toString, I made a method :
public static void logger(String header, String content) {
Date dateActualLog = new Date();
long milliseconds = (dateActualLog.getTime() - dateLastLog.getTime());
Log.d(header, String.valueOf(milliseconds) + " => " + content);
dateLastLog = dateActualLog;
}
(fyi : dateLastLog is a static variable)
I modified the above code like this :
//
// This line takes too long on big responses
//
logger(TAG, "toString ...");
String content = EntityUtils.toString(response.getEntity());
logger(TAG, "toString OK");
Thanks in advance.
Well, the first simple thing to try would be to ensure that your web-server is supplying a correct ContentLength header in the HTTP response. Looking at some version of the source-code for HttpCore's EntityUtils class, we see that if this information is not available, it defaults to using a CharArrayBuffer of just 4k, buffering 1k of data when writing. On the 4th, 5th, and subsequent writes to the CharArrayBuffer (all the way up to 500, you say), it gradually increments the buffer by 1k ... using System.arrayCopy(). Yuck. There's your performance misery right there.
If speed is really important to you however, you'll avoid using EntityUtils entirely. It's just not responsible to turn a stream into a temporary 500k String ... especially on a phone! You'll need to find or write a Base64DecodingInputStream or Base64DecodingReader to wrap your InputStream from response.getEntity().getContent(), and feed that ... instead of a String ... to your parser.

Categories