1

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.
1
  • Did you set specific MIME type according to your file type? Commented Apr 17, 2015 at 9:05

1 Answer 1

1

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();
Sign up to request clarification or add additional context in comments.

3 Comments

Thanks for the reply. Here I am replacing Apache http client with Java URLConnection in my project. So I need it with URLConnnection. Clearly I need to know the equivalent of post.setRequestEntity(entity) in java urlconnnection.Thanks
Please note my requirement is Java URLConnection + POST request + params + file

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.