How to send HTTP POST requests on Java

+1 vote

Consider the following URL:

http://www.example.com/page.php?id=10            

(Here id needs to be sent in a POST request)

I want to send the id = 10 to the server's page.php, which accepts it in a POST method.

How can i do this from within Java?

I tried this :

URL aaa = new URL("http://www.example.com/page.php");
URLConnection ccc = aaa.openConnection();

But I still can't figure out how to send it via POST

May 30, 2018 in Java by developer_1
• 3,350 points
159,531 views
test answer to this reply

Hi, @There,

What exactly reply you want to get? Could you please clarify a bit more?

13 answers to this question.

0 votes

Sending a POST request is easy in vanilla Java. Starting with a URL, we need t convert it to a URLConnection using url.openConnection();. After that, we need to cast it to a HttpURLConnection, so we can access its setRequestMethod() method to set our method. We finally say that we are going to send data over the connection.

URL url = new URL("https://www.example.com/login");
URLConnection con = url.openConnection();
HttpURLConnection http = (HttpURLConnection)con;
http.setRequestMethod("POST"); // PUT is another valid option
http.setDoOutput(true);

We then need to state what we are going to send:

Sending a simple form

A normal POST coming from a http form has a well defined format. We need to convert our input to this format:

Map<String,String> arguments = new HashMap<>();
arguments.put("username", "root");
arguments.put("password", "sjh76HSn!"); // This is a fake password obviously
StringJoiner sj = new StringJoiner("&");
for(Map.Entry<String,String> entry : arguments.entrySet())
    sj.add(URLEncoder.encode(entry.getKey(), "UTF-8") + "=" 
         + URLEncoder.encode(entry.getValue(), "UTF-8"));
byte[] out = sj.toString().getBytes(StandardCharsets.UTF_8);
int length = out.length;

We can then attach our form contents to the http request with proper headers and send it.

http.setFixedLengthStreamingMode(length);
http.setRequestProperty("Content-Type", "application/x-www-form-urlencoded; charset=UTF-8");
http.connect();
try(OutputStream os = http.getOutputStream()) {
    os.write(out);
}
// Do something with http.getInputStream()

Sending JSON

We can also send json using java, this is also easy:

byte[] out = "{\"username\":\"root\",\"password\":\"password\"}" .getBytes(StandardCharsets.UTF_8);
int length = out.length;

http.setFixedLengthStreamingMode(length);
http.setRequestProperty("Content-Type", "application/json; charset=UTF-8");
http.connect();
try(OutputStream os = http.getOutputStream()) {
    os.write(out);
}
// Do something with http.getInputStream()

Remember that different servers accept different content-types for json, see this question.


Sending files with java post

Sending files can be considered more challenging to handle as the format is more complex. We are also going to add support for sending the files as a string, since we don't want to buffer the file fully into the memory.

For this, we define some helper methods:

private void sendFile(OutputStream out, String name, InputStream in, String fileName) {
    String o = "Content-Disposition: form-data; name=\"" + URLEncoder.encode(name,"UTF-8") 
             + "\"; filename=\"" + URLEncoder.encode(filename,"UTF-8") + "\"\r\n\r\n";
    out.write(o.getBytes(StandardCharsets.UTF_8));
    byte[] buffer = new byte[2048];
    for (int n = 0; n >= 0; n = in.read(buffer))
        out.write(buffer, 0, n);
    out.write("\r\n".getBytes(StandardCharsets.UTF_8));
}

private void sendField(OutputStream out, String name, String field) {
    String o = "Content-Disposition: form-data; name=\"" 
             + URLEncoder.encode(name,"UTF-8") + "\"\r\n\r\n";
    out.write(o.getBytes(StandardCharsets.UTF_8));
    out.write(URLEncoder.encode(field,"UTF-8").getBytes(StandardCharsets.UTF_8));
    out.write("\r\n".getBytes(StandardCharsets.UTF_8));
}

We can then use these methods to create a multipart post request as follows:

String boundary = UUID.randomUUID().toString();
byte[] boundaryBytes = 
           ("--" + boundary + "\r\n").getBytes(StandardCharsets.UTF_8);
byte[] finishBoundaryBytes = 
           ("--" + boundary + "--").getBytes(StandardCharsets.UTF_8);
http.setRequestProperty("Content-Type", 
           "multipart/form-data; charset=UTF-8; boundary=" + boundary);

// Enable streaming mode with default settings
http.setChunkedStreamingMode(0); 

// Send our fields:
try(OutputStream out = http.getOutputStream()) {
    // Send our header (thx Algoman)
    out.write(boundaryBytes);

    // Send our first field
    sendField(out, "username", "root");

    // Send a seperator
    out.write(boundaryBytes);

    // Send our second field
    sendField(out, "password", "toor");

    // Send another seperator
    out.write(boundaryBytes);

    // Send our file
    try(InputStream file = new FileInputStream("test.txt")) {
        sendFile(out, "identification", file, "text.txt");
    }

    // Finish the request
    out.write(finishBoundaryBytes);
}
answered May 30, 2018 by Rishabh
• 3,620 points
0 votes

Here is the code I used, It works fine.

HttpClient httpClient = new DefaultHttpClient();
HttpPost httpPost = new HttpPost("http://example.com/");
// Request parameters and other properties.
List<NameValuePair> params = new ArrayList<NameValuePair>();
params.add(new BasicNameValuePair("user", "Bob"));
try {
    httpPost.setEntity(new UrlEncodedFormEntity(params, "UTF-8"));
} catch (UnsupportedEncodingException e) {
    // writing error to Log
    e.printStackTrace();
}
/*
 * Execute the HTTP Request
 */
try {
    HttpResponse response = httpClient.execute(httpPost);
    HttpEntity respEntity = response.getEntity();

    if (respEntity != null) {
        // EntityUtils to get the response content
        String content =  EntityUtils.toString(respEntity);
    }
} catch (ClientProtocolException e) {
    // writing exception to log
    e.printStackTrace();
} catch (IOException e) {
    // writing exception to log
    e.printStackTrace();
}
answered Dec 10, 2018 by Niraj
0 votes

This could be a simple implimentation, A simple way using Apache HTTP Components is

Request.Post("http://www.example.com/page.php")
            .bodyForm(Form.form().add("id", "10").build())
            .execute()
            .returnContent();
answered Dec 10, 2018 by Bhavya
0 votes
You can go through this article for better understanding

http://hc.apache.org/httpcomponents-client-ga/tutorial/html/fluent.html
answered Dec 10, 2018 by Trisha
0 votes

Use http-request that is built on apache http api.

HttpRequest<String> httpRequest = HttpRequestBuilder.createPost("http://www.example.com/page.php", String.class)
.responseDeserializer(ResponseDeserializer.ignorableDeserializer()).build();

public void send(){
   String response = httpRequest.execute("id", "10").get();
}
answered Dec 10, 2018 by Abhinav
0 votes
See this git http-request, this is the easiest method i found

https://github.com/jsunsoftware/http-request
answered Dec 10, 2018 by kriti
0 votes

Use this to send http post requests

HttpRequest<String> httpRequest = HttpRequestBuilder.createPost("https://www.example.com/", String.class)
                                                .responseDeserializer(ResponseDeserializer.toStringDeserializer()).build();
String responseBody = httpRequest.execute(requestParameters).get(); 
answered Dec 10, 2018 by ravi
0 votes

You can use the below function implementation

Request.Post("http://somehost/some-form")
        .addHeader("X-Custom-header", "stuff")
        .viaProxy(new HttpHost("myproxy", 8080))
        .bodyForm(Form.form().add("username", "vip").add("password", "secret").build())
        .execute().saveContent(new File("result.dump"));
answered Dec 10, 2018 by richard072
0 votes

You can call HttpURLConnection.setRequestMethod("POST") and HttpURLConnection.setDoOutput(true).
Actually only the function is needed as POST then becomes the default method.

answered Dec 10, 2018 by Pranav
0 votes

You can use the function as HttpURLConnection.setRequestMethod()

answered Dec 10, 2018 by simplecode
0 votes

How to invoke Thread dump analysis API?

Invoking Thread dump analysis API is very extremely simple:

  1. Register with us. We will email you the API key. This is a one-time setup process. Note: If you have purchased enterprise version with API, you don’t have to register. API key will be provided to you as part of installation instruction.
  2. Post HTTP request to https://api.fastthread.io/fastthread-api?apiKey={API_KEY_SENT_IN_EMAIL}
  3. The body of the HTTP request should contain the Thread dump that needs to be analyzed. You can either send 1 thread dump or multiple thread dumps in the same request.
  4. HTTP Response will be sent back in JSON format. JSON has several important stats about the Thread dump. Primary element to look in the JSON response is: “problem“. API applies several intelligent thread dump analysis patterns and if it detects any issues, it will reported in this “problem” element.

CURL command

Assuming your Thread dump file is located in “./my-thread-dump.txt,” then CURL command to invoke the API is:

curl -X POST --data-binary @./my-thread-dump.txt https://api.fastthread.io/fastthread-api?apiKey={API_KEY_SENT_IN_EMAIL} --header "Content-Type:text"

It can’t get any more simpler than that? Isn’t it?

answered Jun 17, 2019 by Jim
• 810 points

reshown Jun 17, 2019 by Vardhan
0 votes

Below are the steps we need to follow for sending Java HTTP requests using HttpURLConnection class.

  1. Create URL object from the GET/POST URL String.
  2. Call openConnection() method on URL object that returns instance of HttpURLConnection
  3. Set the request method in HttpURLConnection instance, default value is GET.
  4. Call setRequestProperty() method on HttpURLConnection instance to set request header values, such as “User-Agent” and “Accept-Language” etc.
  5. We can call getResponseCode() to get the response HTTP code. This way we know if the request was processed successfully or there was any HTTP error message thrown.
  6. For GET, we can simply use Reader and InputStream to read the response and process it accordingly.
  7. For POST, before we read response we need to get the OutputStream from HttpURLConnection instance and write POST parameters into it.
answered Dec 10, 2020 by Gitika
• 65,770 points
0 votes

With Apache HttpClient

In the old days, this Apache HttpClient is the de facto standard to send an HTTP GET/POST request in Java.

pom.xml

    <dependency>
        <groupId>org.apache.httpcomponents</groupId>
        <artifactId>httpclient</artifactId>
        <version>4.5.10</version>
    </dependency>

HttpClientExample.java

package com.mkyong.http;

import org.apache.http.Header;
import org.apache.http.HttpEntity;
import org.apache.http.HttpHeaders;
import org.apache.http.NameValuePair;
import org.apache.http.client.entity.UrlEncodedFormEntity;
import org.apache.http.client.methods.CloseableHttpResponse;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClients;
import org.apache.http.message.BasicNameValuePair;
import org.apache.http.util.EntityUtils;

import java.io.IOException;
import java.util.ArrayList;
import java.util.List;

public class HttpClientExample {

    // one instance, reuse
    private final CloseableHttpClient httpClient = HttpClients.createDefault();

    public static void main(String[] args) throws Exception {

        HttpClientExample obj = new HttpClientExample();

        try {
            System.out.println("Testing 1 - Send Http GET request");
            obj.sendGet();

            System.out.println("Testing 2 - Send Http POST request");
            obj.sendPost();
        } finally {
            obj.close();
        }
    }

    private void close() throws IOException {
        httpClient.close();
    }

    private void sendGet() throws Exception {

        HttpGet request = new HttpGet("https://www.google.com/search?q=mkyong");

        // add request headers
        request.addHeader("custom-key", "mkyong");
        request.addHeader(HttpHeaders.USER_AGENT, "Googlebot");

        try (CloseableHttpResponse response = httpClient.execute(request)) {

            // Get HttpResponse Status
            System.out.println(response.getStatusLine().toString());

            HttpEntity entity = response.getEntity();
            Header headers = entity.getContentType();
            System.out.println(headers);

            if (entity != null) {
                // return it as a String
                String result = EntityUtils.toString(entity);
                System.out.println(result);
            }

        }

    }

    private void sendPost() throws Exception {

        HttpPost post = new HttpPost("https://httpbin.org/post");

        // add request parameter, form parameters
        List<NameValuePair> urlParameters = new ArrayList<>();
        urlParameters.add(new BasicNameValuePair("username", "abc"));
        urlParameters.add(new BasicNameValuePair("password", "123"));
        urlParameters.add(new BasicNameValuePair("custom", "secret"));

        post.setEntity(new UrlEncodedFormEntity(urlParameters));

        try (CloseableHttpClient httpClient = HttpClients.createDefault();
             CloseableHttpResponse response = httpClient.execute(post)) {

            System.out.println(EntityUtils.toString(response.getEntity()));
        }

    }

}
answered Dec 10, 2020 by Rajiv
• 8,870 points
Thanks working fine

Related Questions In Java

0 votes
1 answer

Is it possible to run a java program from command line on windows?How?

  Let's say your file is in C:\myprogram\ Run ...READ MORE

answered Apr 18, 2018 in Java by sophia
• 1,400 points
2,708 views
0 votes
1 answer

How to pad an integer with zeros on the left in Java?

Use java.lang.String.format() method. String.format("%05d", number ...READ MORE

answered May 31, 2018 in Java by Daisy
• 8,140 points
2,286 views
0 votes
1 answer

How to encode the HTTP URL address in Java?

Use one of the constructors with more ...READ MORE

answered Oct 23, 2018 in Java by Sushmita
• 6,920 points
3,382 views
+1 vote
0 answers

How to install java on linux operating system?

I read good info about java but ...READ MORE

May 16, 2019 in Java by Vicky

reopened Nov 15 by Neelam 668 views
0 votes
2 answers

Performing HTTP POST operation in JAVA

I'm using JSON-Java to build my JSON object: JSONObject json ...READ MORE

answered Nov 26, 2018 in Java by Sushmita
• 6,920 points
4,638 views
0 votes
12 answers

Java - sending HTTP parameters via POST method easily

Below are the steps we need to ...READ MORE

answered Dec 11, 2020 in Java by Rajiv
• 8,870 points
111,108 views
0 votes
2 answers

Send HTTP request in Java

import com.google.api.client.http.GenericUrl; import com.google.api.client.http.HttpRequest; import com.google.api.client.http.HttpResponse; import com.google.api.client.http.HttpTransport; import com.google.api.client.http.javanet.NetHttpTransport; import java.io.IOException; import ...READ MORE

answered Aug 3, 2018 in Java by samarth295
• 2,220 points
1,761 views
+2 votes
13 answers

How does java.net.SocketException: Connection reset happen ?

You can use wireshark to view the ...READ MORE

answered Dec 7, 2018 in Java by tushh
253,305 views
0 votes
1 answer

How to fire and handle HTTP requests

There are 2 options you can go ...READ MORE

answered Jun 13, 2018 in Java by Rishabh
• 3,620 points
1,179 views
0 votes
3 answers

How to parse JSON in Java

import org.json.*; JSONObject obj = new JSONObject(" .... ...READ MORE

answered Aug 20, 2018 in Java by Daisy
• 8,140 points
4,038 views
webinar REGISTER FOR FREE WEBINAR X
REGISTER NOW
webinar_success Thank you for registering Join Edureka Meetup community for 100+ Free Webinars each month JOIN MEETUP GROUP