POST request to server using java URLConnnection with params and file inputs - java

POST request to server using java URLConnnection
I need to send a POST request with the two parameters below:
param1=value1
param2=value2
And also I need to send a file.
In the case of Apache these 2 two(sending params and file) things are handled like below
post.setQueryString(queryString) // queryString is url encoded for eg: param1=value1&param2=value2
post.setRequestEntity(entity) // entity is constructed using file input stream with corresponding format
Please let me know if you have anything related to this problem.
Please note: When I try using Google Chrome REST client plug-in, I am getting the response as below (tried with all request content-types)
UNSUPPORTED FILE FORMAT: 'multipart/form-data' is not a supported content-type
Response code is 400.

Try this API from Apache to send request internally with POST method.
The below is the sample Code to use API
List<org.apache.http.NameValuePair> list =new ArrayList<org.apache.http.NameValuePair>();
HttpPost postMethod = new HttpPost("http://yoururl/ProjectName");
list.add(new BasicNameValuePair("param1", "param1 Value")) ;
postMethod.setEntity(new UrlEncodedFormEntity(list));
HttpClient client = HttpClientBuilder.create().build();
HttpResponse response = client.execute(postMethod);
InputStream is = response.getEntity().getContent();

Related

How to make Java HttpPost NOT include url in body

We have some old java code that POSTs some fields and values to a dotnet5 web api - The api is having problems dealing with the body of the POST as it includes the url/uri as the first part of the body.
The Java sends: http://127.0.0.1:5555?producerRef=GREEN&systemId=78&status=false
But the api is expecting something like: producerRef=GREEN&systemId=78&status=false
as per https://developer.mozilla.org/en-US/docs/Web/HTTP/Methods/POST#example. If we send a test message via Postman then the api has no problems.
This is the Java code:
List<NameValuePair> params = new ArrayList<NameValuePair>(queryParams.size());
for (Map.Entry<String, String> entry : queryParams.entrySet()) {
params.add(new BasicNameValuePair(entry.getKey(), entry.getValue()));
}
// the address is just that, there's NO parameters
HttpPost post = new HttpPost(this.cmAddress.toURI());
post.setEntity(new UrlEncodedFormEntity(params, "UTF-8"));
post.setHeader(HttpHeaders.CONTENT_TYPE, "application/x-www-form-urlencoded");
CloseableHttpResponse response = httpClient.execute(post);
It's quite simple, but always adds the url to the start of the body of the request. If this is the only way to produce this, what could I do to produce something that looks like this: https://developer.mozilla.org/en-US/docs/Web/HTTP/Methods/POST#example
Many Thanks.
This request seems like a GET request rather than a POST since the request params are in the URL. i don't know about the specifications of the Api you're using, but you can try OKHTTP, you can easily copy the code directly from postman
Postman Get example:
Your issue seems to be at below line
HttpPost post = new HttpPost(this.cmAddress.toURI());
This is the only place which will set the POST url ( another way is to use setURI which is not called anywhere in the code sample you have shared).
If you can use a debugger try checking the value of cmAdress variable

How to set Headers if I am using responde.sendRedirect

Previous scenario:-
User logins through Portal and user clicks on some link, the portal sends the request which contains Headers(user name) to reporting server to retrieve report .
Current Scenario:-
The portal was re-written and Headers are now being in JSON format, the Header values through which the authentication was being done is named in a different way. We thought to intercept the request and rearrange the Headers in a way how the reporting server reads so that request can go through.
We thought of deploying this new Interceptor application in a new Tomcat server on the same box where Reporting server is , and I cannot use RequestDispatcher.forward , and sendRedirect if I use nullifies any Header values which I add before doing sendRedirect as browser will issue a new request.
I tried using HttpClient , to open a new Http connection to reporting server with adding Header values , but when I check the same in Fiddler or HTTP Header spy in my chrome browser I cannot see any Header values in the client request object. And I am trying to capture the response object from reporting server and set the same in my original request , and set that in the original response object in my servlet to push to client browser. But as my Header values are not getting set in HTTPClient Post request the request is never fulfilled.
Below is the same code for creating HTTPClient from my interceptor servlet.
String url = "someurl";
HttpClient client = HttpClientBuilder.create().build();
//HttpGet get = new HttpGet();
HttpPost post = new HttpPost(url);
try {
String smUser = "<user name>";
String grps = "<some values>";
post.addHeader(<headerKey1>,<smUser>);
post.addHeader(<headerkey2>, grps);
HttpResponse response = client.execute(post);
BufferedReader buff = new BufferedReader(new InputStreamReader(
response.getEntity().getContent()));
response.getEntity().getContent();
String inputLine;
StringBuffer html = new StringBuffer();
while ((inputLine = buff.readLine()) != null) {
html.append(inputLine);
}
buff.close();
System.out.println("URL Content... \n" + html.toString());
I know I can use url rewritting , but that is not an option , let me know if there is any other way through which my interceptor can change the Header values and pass the request to reporting server , so that user can access reports.
I alse was blockd by this issue. Code like below, but the header I added hasn't been sent to target service. By the way, there're two different services
response.setHeader(key, value)
response.sendRedirect(target_url)

POST Request with multipart/form-data Java code

I'm using Activiti and Eclipse. Now I want to upload my process to web UI through restful API.
Follow the document, I test it successfully in Postman.
My request has a basic auth:
enter image description here
And this is body with a file to upload:
enter image description here
My problem is I don't know how to do that request in Java code, I write some code following some Stack's post but it doesn't work.
HttpClient httpClient = HttpClientBuilder.create().build();
HttpPost request = new HttpPost("http://localhost:8080/activiti-rest/service/repository/deployments");
request.addHeader("content-type","multipart/form-data");
//convert credentials to base64
byte[] credentials = Base64.encodeBase64(("kermit:kermit").getBytes(StandardCharsets.UTF_8));
request.setHeader("Authorization", "Basic " + new String(credentials, StandardCharsets.UTF_8));
request.setEntity(new FileEntity(new File("C:/Users/ISC-HaoNMN/Desktop/ActivitiProcess.bar")));
httpClient.execute(request);
Can someone give me a sample code. Thank you!

Sending a key and file using MultipartEntityBuilder

I don't have much experience with networking and my Googling skills don't seem to get me any further than this.
I need to send a file to a server with "file" being the HTTP POST key. Here is what I have:
MultipartEntityBuilder mpEntity = MultipartEntityBuilder.create();
mpEntity.addBinaryBody("file", image);//set up the object to send
HttpPut put = new HttpPut("http://address:port");
put.setEntity(mpEntity.build());//put the object to be sent
//try sending
try {
HttpResponse response = client.execute(put);
...
I'm getting a 404 error when I process the response using an InputStream. The server is up and running and works fine when I test it from the terminal.
Add the content type and the name of the file to the binary body like this:
mpEntity.addBinaryBody("file", image, ContentType.create("image/jpeg"), "image_name.jpg");

Downloading a file using a REST POST call in java

I have a REST service which returns a file when it is called via a POST call with an XML file as the parameter. My goal is to access the service using a client (a simple httppost call in a java class). So far, I am doing as below:
DefaultHttpClient defaultHtppclient = new DefaultHttpClient();
HttpPost postRequest = new HttpPost("resturl");
StringEntity input = new StringEntity("input xml file ");
input.setContentType("application/xml");
postRequest.setEntity(input);
HttpResponse response = defaultHtppclient.execute(postRequest);
I am getting the contents of the file when I convert the response using :
String content = EntityUtils.toString(response.getEntity());
But I am struggling to download the file as such from the java class. When I trigger the URL in Firefox HTTP resource test. I am getting the headers as:
Content-Disposition: attachment; filename = filenameFromserver
Content-Type: application/octet-stream
Is there any way to download the file as such from the client ?
The call you're making is expecting application/xml, the server is sending you an octet-stream.
You'll have to read in the bytes it's sending you and write them out to the file that you want. I'd recommend searching around on how to read in an octet stream.
For an example take a look at this post:
Reading binary file from URLConnection

Categories

Resources