How to POST NON-JSON request using Apache HttpClient? - java

I am to hitting an API which will return string data and as well I want to send data of string type(textfile in a paragraph).

You can use Apache httpcomponents, with http entities
Here is an example for sending a file in your POST request:
File file = new File("somefile.txt");
FileEntity entity = new FileEntity(file, ContentType.create("text/plain", "UTF-8"));
HttpPost httppost = new HttpPost("http://localhost/action.do");
httppost.setEntity(entity);
If you want a text content, you can use StringEntity:
StringEntity myEntity = new StringEntity("something", ContentType.create("text/plain", "UTF-8"));

Related

post encrypted json to external api in java

excuse me everyone, I'm currently having problems connecting my spring boot application with an open api IoT. to send data to the open api, the request body must be encrypted and sent in json form. I have followed the available documentation, but the response says that the request parameter must be in json format.
here is my program code:
HttpPost httppost = new HttpPost(url);
httppost.addHeader("x-random-key", randomSecretKey);
httppost.addHeader("x-access-key", xAccessKey);
httppost.addHeader("Content-type", "application/json;charset=UTF-8");
httppost.addHeader("sys_code", "901");
httppost.addHeader("lang", "_en_US");
String encryptedRequestBody = encrypt(request.toString(), randomMessage);
StringEntity strEntity = new StringEntity(encryptedRequestBody);
strEntity.setContentType("application/json");
httppost.setEntity(strEntity);
CloseableHttpResponse response = httpclient.execute(httppost);
HttpEntity entity = response.getEntity();
InputStream inputStream = entity.getContent();

File attachment with REST API

The below code is working fine to attach file in JIRA, only one problem is here
I can't use MultipartEntityBuilder as it needed to add new dependency in pom and that is not permissible , can any one please suggest which basic API I can use there? thanks in advance
CloseableHttpClient httpClient = HttpClientBuilder.create().build();
HttpPost postRequest = new HttpPost("https://xxxx.zzzz.net/rest/api/2/issue/" + issueID +"/attachments");
postRequest.setHeader("Authorization", "Basic <AUTHSTRING>");
postRequest.setHeader("X-Atlassian-Token", "nocheck");
File file = new File("C:\\Users\\MKumar\\Desktop\\Oauth_JIRA.rtf");
URL url = new URL("C:\\Users\\MKumar\\Desktop\\Oauth_JIRA.rtf");
MultipartEntityBuilder builder = MultipartBodyBuilder.create();
// This attaches the file to the POST:
builder.addBinaryBody(
"file",
new FileInputStream(file),
ContentType.MULTIPART_FORM_DATA,
file.getName()
);
HttpEntity multipart = builder.build();
postRequest.setEntity(multipart);
HttpResponse response = httpClient.execute(postRequest);
org.apache.http.entity.mime.MultipartEntity is deprecated as a result you'll have to use MultipartEntityBuilder.
For more related post please see this thread

Unable to download pdf file by consuming REST webservice in Grails

I am using Grails Plugin rest=0.7 for consuming a Rest Webservice.
Everything works fine when the response from the service is xml but in case if response is file type like pdf it must start downloading on sending the request but the downloading is not starting at all.
The below code in implemented in a grails service.
String httpUrl = 'http://abc.com/myService'
String data = '<methodcall protocol="2" method="avalidmethodname"><cmdid/><data><project_id>1</project_id><user_id>2</user_id><operation>ABC</operation><filter><status_type_id>1</status_type_id><scope_bits>00</scope_bits></filter></data></methodcall>'
String respText = ''
HttpClient httpClient = new DefaultHttpClient()
HttpResponse response
try {
HttpPost httpPost = new HttpPost(httpUrl)
httpPost.setHeader("Content-Type", "text/xml")
HttpEntity reqEntity = new StringEntity(data, "UTF-8")
reqEntity.setContentType("text/xml")
reqEntity.setChunked(true)
httpPost.setEntity(reqEntity)
response = httpClient.execute(httpPost)
// HttpEntity resEntity = response.getEntity()
// respText = resEntity.getContent().text
}
finally {
httpClient.getConnectionManager().shutdown()
}
return response
// return respText
The commented lines in code is for the case of xml response.
Please help me to resolve this problem, i am not sure the approach i am using is valid in case of file response from the webservice.
Try adding
response.setContentType("text/pdf");
before
response = httpClient.execute(httpPost);

GZip POST request with HTTPClient in Java

I need to send a POST request to a web server which includes a gzipped request parameter. I'm using Apache HttpClient and I've read that it supports Gzip out of the box, but I can't find any examples of how to do what I need. I'd appreciate it if anyone could post some examples of this.
You need to turn that String into a gzipped byte[] or (temp) File first. Let's assume that it's not an extraordinary large String value so that a byte[] is safe enough for the available JVM memory:
String foo = "value";
ByteArrayOutputStream baos = new ByteArrayOutputStream();
try (GZIPOutputStream gzos = new GZIPOutputStream(baos)) {
gzos.write(foo.getBytes("UTF-8"));
}
byte[] fooGzippedBytes = baos.toByteArray();
Then, you can send it as a multipart body using HttpClient as follows:
MultipartEntity entity = new MultipartEntity();
entity.addPart("foo", new InputStreamBody(new ByteArrayInputStream(fooGzippedBytes), "foo.txt"));
HttpPost post = new HttpPost("http://example.com/some");
post.setEntity(entity);
HttpClient client = new DefaultHttpClient();
HttpResponse response = client.execute(post);
// ...
Note that HttpClient 4.1 supports the new ByteArrayBody which can be used as follows:
entity.addPart("foo", new ByteArrayBody(fooGzippedBytes, "foo.txt"));

InputStreamBody in HttpMime 4.0.3 settings for content-length

I am trying to send a multi part formdata post through my java code. Can someone tell me how to set Content Length in the following?? There seem to be headers involved when we use InputStreamBody which implements the ContentDescriptor interface. Doing a getContentLength on the InputStreamBody gives me -1 after i add the content. I subclassed it to give contentLength the length of my byte array but am not sure if other headers required by ContentDescriptor will be set for a proper POST.
HttpClient httpclient = new DefaultHttpClient();
HttpPost httpPost = new HttpPost(myURL);
ContentBody cb = new InputStreamBody(new ByteArrayInputStream(bytearray), myMimeType, filename);
//ContentBody cb = new ByteArrayBody(bytearray, myMimeType, filename);
MultipartEntity mpentity = new MultipartEntity(HttpMultipartMode.BROWSER_COMPATIBLE);
mpentity.addPart("key", new StringBody("SOME_KEY"));
mpentity.addPart("output", new StringBody("SOME_NAME"));
mpentity.addPart("content", cb);
httpPost.setEntity(mpentity);
HttpResponse response = httpclient.execute(httpPost);
HttpEntity resEntity = response.getEntity();
I'm the author of the ByteArrayBody class you have commented out.
I wrote it because I faced the same issue you did. The original Jira ticket is here: https://issues.apache.org/jira/browse/HTTPCLIENT-1014
So, since you already have a byte[], either upgrade HttpMime to the latest version, 4.1-beta1, which includes this class. Or copy the code from the Jira issue into your own project.
The ByteArrayBody class will do exactly what you need.

Categories

Resources