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.
Robert
  • 1,286
  • 1
  • 17
  • 37
Mohan G
  • 11
  • 4

1 Answers1

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();
Rookie007
  • 1,229
  • 2
  • 18
  • 50
  • 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 – Mohan G Apr 17 '15 at 10:41
  • Please note my requirement is Java URLConnection + POST request + params + file – Mohan G Apr 17 '15 at 12:05
  • did u check this out http://stackoverflow.com/questions/2026260/java-how-to-use-urlconnection-to-post-request-with-authorization – Rookie007 Apr 17 '15 at 18:06