2

I need to replicate a Postman POST in Java. Usually I had to make an HttpPost with only params in URL, so it was easy to build:

ArrayList<NameValuePair> postParameters = new ArrayList<NameValuePair>();
postParameters.add(new BasicNameValuePair("username", username));
post.setEntity(new UrlEncodedFormEntity(postParameters, Consts.UTF_8));

But what I have to do if I have a POST like the image below where there are Params in URL and Body TOGETHER?? POST call with Params and Body Now I'm making the HttpPost like this:

HttpClient client = HttpClientBuilder.create().build();
HttpPost post = new HttpPost("someUrls.com/upload");
ArrayList<NameValuePair> postParameters = new ArrayList<NameValuePair>();
postParameters.add(new BasicNameValuePair("username", username));
postParameters.add(new BasicNameValuePair("password", password));
postParameters.add(new BasicNameValuePair("owner", owner));
postParameters.add(new BasicNameValuePair("destination", destination));
try{
    post.setEntity(new UrlEncodedFormEntity(postParameters, Consts.UTF_8));
    HttpResponse httpResponse = client.execute(post);
    //Do something
}catch (Exception e){
    //Do something
}

But how I put "filename" and "filedata" params in the Body together with the params in the URL? Actually I'm using org.Apache library, but i could consider also others library.

Thanks to anybody that will help!

Chiuccolo
  • 53
  • 1
  • 10
  • Could you please share more of your code i.e. how are you making the requests, what type of object is `post` etc. Also you should consider, if you can, using a library to handle the requests e.g. `okhttp` – Guy Grin Mar 21 '18 at 08:53
  • @GuyGrin Ok, I've added an example. Thanks for the attention. – Chiuccolo Mar 21 '18 at 09:12

3 Answers3

0

You can use below code to pass the body parameters as "application/x-www-form-urlencoded" in POST method call

package han.code.development;

import java.io.BufferedReader;
import java.io.InputStreamReader;
import java.io.PrintWriter;
import java.net.URL;

import javax.net.ssl.HttpsURLConnection;

public class HttpPost
{
    public String getDatafromPost()
    {
        BufferedReader br=null;
        String outputData;
        try
        {
            String urlString="https://www.google.com"; //you can replace that with your URL
            URL url=new URL(urlString);
            HttpsURLConnection connection=(HttpsURLConnection) url.openConnection();
            connection.setRequestMethod("POST");
            connection.addRequestProperty("Content-Type", "application/x-www-form-urlencoded");
            connection.addRequestProperty("Authorization", "Replace with your token"); // if you have any accessToken to authorization, just replace
            connection.setDoOutput(true);
            String data="filename=file1&filedata=asdf1234qwer6789";

            PrintWriter out;
            if((data!=null)) 
            {
                 out = new PrintWriter(connection.getOutputStream());
                 out.println(data);
                 out.close();
            }
            System.out.println(connection.getResponseCode()+" "+connection.getResponseMessage());
            br=new BufferedReader(new InputStreamReader(connection.getInputStream()));
            StringBuilder sb=new StringBuilder();
            String str=br.readLine();
            while(str!=null)
            {
                sb.append(str);
                str=br.readLine();
            }

            outputData=sb.toString();
            return outputData;
       }
       catch(Exception e)
       {
           e.printStackTrace();
       }
       return null;
   }
   public static void main(String[] args)
   {
       HttpPost post=new HttpPost();
       System.out.println(post.getDatafromPost());
   }
}
0

I think this question, and this question are about similar issues and both have good answers.

I would recommend using this library as it is well maintained and simple to use if you want.

Guy Grin
  • 1,968
  • 2
  • 17
  • 38
0

I've resolved making this way:

  1. put on POST URL header params;
  2. adding as MultipartEntity the filename and filedata.

Here the code....

private boolean uploadQueue(String username, String password, String filename, byte[] fileData)
{
    HttpClient client = HttpClientBuilder.create().build();
    String URL = "http://post.here.com:8080/";
    HttpPost post = new HttpPost(URL +"?username="+username+"&password="password);

    try
    {
        MultipartEntityBuilder entityBuilder = MultipartEntityBuilder.create();
        entityBuilder.addBinaryBody("filedata", fileData, ContentType.DEFAULT_BINARY, filename);
        entityBuilder.addTextBody("filename", filename);

        post.setEntity(entityBuilder.build());

        HttpResponse httpResponse = client.execute(post);

        if (httpResponse.getStatusLine().getStatusCode() == HttpStatus.SC_OK)
        {
            logger.info(EntityUtils.toString(httpResponse.getEntity()));

            return true;
        } 
        else
        {
            logger.info(EntityUtils.toString(httpResponse.getEntity()));

            return false;
        }
    }
    catch (Exception e)
    {
        logger.error("Error during Updload Queue phase:"+e.getMessage());
    }

    return false;
}
Chiuccolo
  • 53
  • 1
  • 10