9

I want to make a simple POST call in Java,
I am getting a 200 response code but, with the wrong response message,
I am told there is a different way to make a Post call when using a form data.

Following is my current Java code to make the post call -

private String makePostCall(){
        try {
            String url = "http://someIp/trusted";
            HttpClient client = new DefaultHttpClient();
            HttpPost post = new HttpPost(url);

            // add header
            List<NameValuePair> urlParameters = new ArrayList<NameValuePair>();
            urlParameters.add(new BasicNameValuePair("username", "app_user"));

            post.setEntity(new UrlEncodedFormEntity(urlParameters));

            HttpResponse response = client.execute(post);
            System.out.println("\nSending 'POST' request to URL : " + url);
            System.out.println("Post parameters : " + post.getEntity());
            System.out.println("Response Code : " + response.getStatusLine().getStatusCode());

            BufferedReader rd = new BufferedReader(new InputStreamReader(response.getEntity().getContent()));
            StringBuffer result = new StringBuffer();
            String line = "";
            while ((line = rd.readLine()) != null) {
                result.append(line);
            }

            System.out.println(result.toString());
            return result.toString();

        } catch (Exception e) {
            e.printStackTrace();
            return null;
        }
    }

Following is the Post call sample that is working through Postman app - enter image description here

I am referring the following website -
https://www.mkyong.com/java/how-to-send-http-request-getpost-in-java/


The expected outcome of the post call is supposed to be a Token ie. a String value, current response is -1.

6
  • What's the question? give expected vs actual result Commented Aug 15, 2017 at 6:35
  • The expected outcome of the post call is supposed to be a Token ie. a String value, current response is -1. Commented Aug 15, 2017 at 6:38
  • what is the status code of response? Commented Aug 15, 2017 at 6:42
  • see stackoverflow.com/questions/5769717/… Commented Aug 15, 2017 at 6:43
  • I am getting a 200 response but, I am told I am passing the form data ie. app_user the wrong way or something, check the Postman screenshot. Commented Aug 15, 2017 at 6:47

2 Answers 2

9

These answers are correct, but I struggled to get this to a working code. So, let me provide a general and working answer which can be reused.

private static RequestConfig requestConfig = RequestConfig.custom().build();

public HttpResponse postWithFormData(String url, List<NameValuePair> params) throws IOException {
        // building http client
        HttpClient httpClient = HttpClientBuilder.create().setDefaultRequestConfig(requestConfig).build();
        HttpPost request = new HttpPost(url);

        // adding the form data
        request.setEntity(new UrlEncodedFormEntity(params));
        return httpClient.execute(request);
    }

List<NameValuePair> urlParameters = new ArrayList<>();

// add any number of form data
urlParameters.add(new BasicNameValuePair("form_key_1", "form_value_1");
urlParameters.add(new BasicNameValuePair("form_key_2", "form_value_2");

// Getting the HTTP Response and processing it
HttpResponse response = postWithFormData("http_url", urlParameters);
HttpEntity entity = response.getEntity();
// String of the response
String responseString = EntityUtils.toString(entity);
// JSON of the response (use this only if the response is a JSON)
JSONObject responseObject = new JSONObject(responseString);

These are my main imports, in case anyone gets confused on what to import.

import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.NameValuePair;
import org.apache.http.message.BasicNameValuePair;
import org.apache.http.util.EntityUtils;
import org.json.JSONObject;
import org.apache.http.client.HttpClient;
import org.apache.http.client.entity.UrlEncodedFormEntity;
Sign up to request clarification or add additional context in comments.

4 Comments

What is your requestConfig ? On line 3
org.apache.http.client.config.RequestConfig
Worked for me with some slight changes as per my use case. Thumbs up.
Functional example with all required imports and dependencies on replit, fill in your URL/data. replit.com/@domjancik/JavaFormDataPost
5

Give a try by setting content type multipart/form-data explicitly,

post.setHeader("Content-Type", "multipart/form-data");

In your code ,

post.setEntity(new UrlEncodedFormEntity(urlParameters)); 
post.setHeader("Content-Type", "multipart/form-data");

Comments

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.