My html page

How to send simple http post request with post parameters in java

I need a simple code example of sending http post request with post parameters that I get from form inputs. I have found Apache HTTPClient, it has very reach API and lots of sophisticated examples, but I couldn’t find a simple example of sending http post request with input parameters and getting text response. Update: I’m interested in Apache HTTPClient v.4.x, as 3.x is deprecated.

5 Answers 5

Here’s the sample code for Http POST, using Apache HTTPClient API.

import java.io.InputStream; import org.apache.commons.httpclient.HttpClient; import org.apache.commons.httpclient.methods.PostMethod; public class PostExample < public static void main(String[] args)< String url = "http://www.google.com"; InputStream in = null; try < HttpClient client = new HttpClient(); PostMethod method = new PostMethod(url); //Add any parameter if u want to send it with Post req. method.addParameter("p", "apple"); int statusCode = client.executeMethod(method); if (statusCode != -1) < in = method.getResponseBodyAsStream(); >System.out.println(in); > catch (Exception e) < e.printStackTrace(); >> > 

Thank you, Sumit. I need such example, but your example is using Apache HttpClient v. 3.x, which is deprecated (even I couldn’t find 3.x version jars in their download page). Now they suggest HttpClient v.4.1, which has different API, but I don’t find how to put post parameters with this API.

I have found the jars for httpClient v.3 and it works for me, but anyway I wonder why it’s such complicated to send simple post request with v. 4.1 and in java in general.

I pulled this code from an Android project by Andrew Gertig that I have used in my application. It allows you to do an HTTPost. If I had time, I would create an POJO example, but hopefully, you can dissect the code and find what you need.

private void postEvents() < DefaultHttpClient client = new DefaultHttpClient(); /** FOR LOCAL DEV HttpPost post = new HttpPost("http://192.168.0.186:3000/events"); //works with and without "/create" on the end */ HttpPost post = new HttpPost("http://cold-leaf-59.heroku.com/myevents"); JSONObject holder = new JSONObject(); JSONObject eventObj = new JSONObject(); Double budgetVal = 99.9; budgetVal = Double.parseDouble(eventBudgetView.getText().toString()); try < eventObj.put("budget", budgetVal); eventObj.put("name", eventNameView.getText().toString()); holder.put("myevent", eventObj); Log.e("Event JSON", "Event JSON = "+ holder.toString()); StringEntity se = new StringEntity(holder.toString()); post.setEntity(se); post.setHeader("Content-Type","application/json"); >catch (UnsupportedEncodingException e) < Log.e("Error",""+e); e.printStackTrace(); >catch (JSONException js) < js.printStackTrace(); >HttpResponse response = null; try < response = client.execute(post); >catch (ClientProtocolException e) < e.printStackTrace(); Log.e("ClientProtocol",""+e); >catch (IOException e) < e.printStackTrace(); Log.e("IO",""+e); >HttpEntity entity = response.getEntity(); if (entity != null) < try < entity.consumeContent(); >catch (IOException e) < Log.e("IO E",""+e); e.printStackTrace(); >> Toast.makeText(this, "Your post was successfully uploaded", Toast.LENGTH_LONG).show(); > 

Источник

Читайте также:  Java blocked exception error

Java HTTP GET/POST request

This tutorial shows how to send a GET and a POST request in Java. We use the built-in HttpURLConnection class and the standard Java and Apache HttpClient class.

HTTP

The is an application protocol for distributed, collaborative, hypermedia information systems. HTTP is the foundation of data communication for the World Wide Web.

In the examples, we use httpbin.org , which is a freely available HTTP request and response service, and the webcode.me , which is a tiny HTML page for testing.

HTTP GET

The HTTP GET method requests a representation of the specified resource. Requests using GET should only retrieve data.

HTTP POST

The HTTP POST method sends data to the server. It is often used when uploading a file or when submitting a completed web form.

GET request with Java HttpClient

Since Java 11, we can use the java.net.http.HttpClient .

package com.zetcode; import java.io.IOException; import java.net.URI; import java.net.http.HttpClient; import java.net.http.HttpRequest; import java.net.http.HttpResponse; public class GetRequestEx < public static void main(String[] args) throws IOException, InterruptedException < HttpClient client = HttpClient.newHttpClient(); HttpRequest request = HttpRequest.newBuilder() .uri(URI.create("http://webcode.me")) .build(); HttpResponseresponse = client.send(request, HttpResponse.BodyHandlers.ofString()); System.out.println(response.body()); > >

We create a GET request to the webcode.me webpage.

HttpClient client = HttpClient.newHttpClient();

A new HttpClient is created with the newHttpClient factory method.

HttpRequest request = HttpRequest.newBuilder() .uri(URI.create("http://webcode.me")) .build();

We build a synchronous request to the webpage. The default method is GET.

HttpResponse response = client.send(request, HttpResponse.BodyHandlers.ofString()); System.out.println(response.body());

We send the request and retrieve the content of the response and print it to the console.

        

Today is a beautiful day. We go swimming and fishing.

Hello there. How are you?

Java HTTP POST request with Java HttpClient

The next example creates a POST request with Java HttpClient.

implementation 'com.fasterxml.jackson.core:jackson-databind:2.13.3'

We need the jackson-databind dependency.

package com.zetcode; import com.fasterxml.jackson.databind.ObjectMapper; import java.io.IOException; import java.net.URI; import java.net.http.HttpClient; import java.net.http.HttpRequest; import java.net.http.HttpResponse; import java.util.HashMap; public class PostRequestEx < public static void main(String[] args) throws IOException, InterruptedException < var values = new HashMap() >; var objectMapper = new ObjectMapper(); String requestBody = objectMapper .writeValueAsString(values); HttpClient client = HttpClient.newHttpClient(); HttpRequest request = HttpRequest.newBuilder() .uri(URI.create("https://httpbin.org/post")) .POST(HttpRequest.BodyPublishers.ofString(requestBody)) .build(); HttpResponse response = client.send(request, HttpResponse.BodyHandlers.ofString()); System.out.println(response.body()); > >

We send a POST request to the https://httpbin.org/post page.

var values = new HashMap() >; var objectMapper = new ObjectMapper(); String requestBody = objectMapper .writeValueAsString(values);

First, we build the request body with the Jackson’s ObjectMapper .

HttpClient client = HttpClient.newHttpClient(); HttpRequest request = HttpRequest.newBuilder() .uri(URI.create("https://httpbin.org/post")) .POST(HttpRequest.BodyPublishers.ofString(requestBody)) .build();

We build the POST request. With BodyPublishers.ofString we create a new BodyPublisher . It converts high-level Java objects into a flow of byte buffers suitable for sending as a request body.

HttpResponse response = client.send(request, HttpResponse.BodyHandlers.ofString()); System.out.println(response.body());

We send the request and retrieve the response.

< "args": <>, "data": "", "files": <>, "form": <>, "headers": < "Content-Length": "43", "Host": "httpbin.org", "User-Agent": "Java-http-client/12.0.1" >, "json": < "name": "John Doe", "occupation": "gardener" >, . "url": "https://httpbin.org/post" >

Java HTTP GET request with HttpURLConnection

The following example uses HttpURLConnection to create a GET request.

package com.zetcode; import java.io.BufferedReader; import java.io.IOException; import java.io.InputStreamReader; import java.net.HttpURLConnection; import java.net.URL; public class GetRequestEx < private static HttpURLConnection con; public static void main(String[] args) throws IOException < var url = "http://webcode.me"; try < var myurl = new URL(url); con = (HttpURLConnection) myurl.openConnection(); con.setRequestMethod("GET"); StringBuilder content; try (BufferedReader in = new BufferedReader( new InputStreamReader(con.getInputStream()))) < String line; content = new StringBuilder(); while ((line = in.readLine()) != null) < content.append(line); content.append(System.lineSeparator()); >> System.out.println(content.toString()); > finally < con.disconnect(); >> >

The example retrieves a web page with HTTP GET request.

Читайте также:  Order forms in html

We retrieve the contents of this tiny webpage.

var myurl = new URL(url); con = (HttpURLConnection) myurl.openConnection();

A connection to the specified URL is created.

We set the request method type with the setRequestMethod method.

try (BufferedReader in = new BufferedReader( new InputStreamReader(con.getInputStream()))) 

An input stream is created from the HTTP connection object. The input stream is used to read the returned data.

content = new StringBuilder();

We use StringBuilder to build the content string.

while ((line = in.readLine()) != null)

We read the data from the input stream line by line with readLine . Each line is added to StringBuilder . After each line we append a system-dependent line separator.

System.out.println(content.toString());

We print the content to the terminal.

Java HTTP POST request with HttpURLConnection

The following example uses HttpURLConnection to create a POST request.

package com.zetcode; import java.io.BufferedReader; import java.io.DataOutputStream; import java.io.IOException; import java.io.InputStreamReader; import java.net.HttpURLConnection; import java.net.URL; import java.nio.charset.StandardCharsets; public class PostRequestEx < private static HttpURLConnection con; public static void main(String[] args) throws IOException < var url = "https://httpbin.org/post"; var urlParameters = "name=Jack&occupation=programmer"; byte[] postData = urlParameters.getBytes(StandardCharsets.UTF_8); try < var myurl = new URL(url); con = (HttpURLConnection) myurl.openConnection(); con.setDoOutput(true); con.setRequestMethod("POST"); con.setRequestProperty("User-Agent", "Java client"); con.setRequestProperty("Content-Type", "application/x-www-form-urlencoded"); try (var wr = new DataOutputStream(con.getOutputStream())) < wr.write(postData); >StringBuilder content; try (var br = new BufferedReader( new InputStreamReader(con.getInputStream()))) < String line; content = new StringBuilder(); while ((line = br.readLine()) != null) < content.append(line); content.append(System.lineSeparator()); >> System.out.println(content.toString()); > finally < con.disconnect(); >> >

The example sends a POST request to https://httpbin.org/post .

var urlParameters = "name=Jack&occupation=programmer"; byte[] postData = urlParameters.getBytes(StandardCharsets.UTF_8);

We are going to write these two key/value pairs. We transform the strings into an array of bytes.

var myurl = new URL(url); con = (HttpURLConnection) myurl.openConnection();

A connection to the URL is opened.

With the setDoOutput method we indicate that we are going to write data to the URL connection.

The HTTP request type is set with setRequestMethod .

con.setRequestProperty("User-Agent", "Java client");

We set the user age property with the setRequestProperty method.

try (DataOutputStream wr = new DataOutputStream(con.getOutputStream()))

We write the bytes or our data to the URL connection.

StringBuilder content; try (var br = new BufferedReader( new InputStreamReader(con.getInputStream()))) < String line; content = new StringBuilder(); while ((line = br.readLine()) != null) < content.append(line); content.append(System.lineSeparator()); >> System.out.println(content.toString());

We read the input stream of the connection and write the retrieved content to the console.

Java HTTP GET request with Apache HttpClient

The following example uses Apache HttpClient to create a GET request.

implementation 'org.apache.httpcomponents:httpclient:4.5.13'

For the examples, we need this Maven dependency.

package com.zetcode; import java.io.BufferedReader; import java.io.IOException; import java.io.InputStreamReader; import org.apache.http.HttpResponse; import org.apache.http.client.methods.HttpGet; import org.apache.http.impl.client.CloseableHttpClient; import org.apache.http.impl.client.HttpClientBuilder; public class GetRequestEx < public static void main(String[] args) throws IOException < try (CloseableHttpClient client = HttpClientBuilder.create().build()) < var request = new HttpGet("http://webcode.me"); HttpResponse response = client.execute(request); var bufReader = new BufferedReader(new InputStreamReader( response.getEntity().getContent())); var builder = new StringBuilder(); String line; while ((line = bufReader.readLine()) != null) < builder.append(line); builder.append(System.lineSeparator()); >System.out.println(builder); > > >

The example sends a GET request to read the home page of the specified webpage.

try (CloseableHttpClient client = HttpClientBuilder.create().build()) 

CloseableHttpClient is built with HttpClientBuilder .

var request = new HttpGet("http://webcode.me");

HttpGet is used to create an HTTP GET request.

HttpResponse response = client.execute(request);

We execute the request and get a response.

var bufReader = new BufferedReader(new InputStreamReader( response.getEntity().getContent()));

From the response object, we read the content.

while ((line = bufReader.readLine()) != null)

We read the content line by line and dynamically build a string message.

Java HTTP POST with Apache HttpClient

The following example uses HttpPost to create a POST request.

package com.zetcode; import java.io.BufferedReader; import java.io.IOException; import java.io.InputStreamReader; import org.apache.http.HttpResponse; import org.apache.http.client.methods.HttpPost; import org.apache.http.entity.StringEntity; import org.apache.http.impl.client.CloseableHttpClient; import org.apache.http.impl.client.HttpClientBuilder; public class PostRequestEx < public static void main(String[] args) throws IOException < try (CloseableHttpClient client = HttpClientBuilder.create().build()) < var request = new HttpPost("https://httpbin.org/post"); request.setHeader("User-Agent", "Java client"); request.setEntity(new StringEntity("My test data")); HttpResponse response = client.execute(request); var bufReader = new BufferedReader(new InputStreamReader( response.getEntity().getContent())); var builder = new StringBuilder(); String line; while ((line = bufReader.readLine()) != null) < builder.append(line); builder.append(System.lineSeparator()); >System.out.println(builder); > > >

The example sends a POST request to https://httpbin.org/post .

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

HttpPost is used to create a POST request.

request.setEntity(new StringEntity("My test data"));

The data is set with the setEntity method.

request.setHeader("User-Agent", "Java client");

We set a header to the request with the setHeader method.

HttpResponse response = client.execute(request);

We execute the request and get the response.

var bufReader = new BufferedReader(new InputStreamReader( response.getEntity().getContent())); var builder = new StringBuilder(); String line; while ((line = bufReader.readLine()) != null) < builder.append(line); builder.append(System.lineSeparator()); >System.out.println(builder);

We read the response and print it to the terminal.

In this article we have created a GET and a POST request in Java with HttpURLConnection and standard Java and Apache HttpClient .

Author

My name is Jan Bodnar and I am a passionate programmer with many years of programming experience. I have been writing programming articles since 2007. So far, I have written over 1400 articles and 8 e-books. I have over eight years of experience in teaching programming.

Источник

Оцените статью