How to send HTTP request GET/POST in Java

来源:互联网 发布:matlab取矩阵中的元素 编辑:程序博客网 时间:2024/06/04 18:46

In this article, we will show you two examples to make HTTP GET/POST request via following APIs

  1. Standard HttpURLConnection.
  2. Apache HttpClient library.

1. Java HttpURLConnection example

This example uses HttpURLConnection (http) and HttpsURLConnection (https) to

  1. Send an HTTP GET request to Google.com to get the search result.
  2. Send an HTTP POST request to Apple.com search form to check the product detail.
HttpURLConnectionExample.java
package com.mkyong;import java.io.BufferedReader;import java.io.DataOutputStream;import java.io.InputStreamReader;import java.net.HttpURLConnection;import java.net.URL;import javax.net.ssl.HttpsURLConnection;public class HttpURLConnectionExample {private final String USER_AGENT = "Mozilla/5.0";public static void main(String[] args) throws Exception {HttpURLConnectionExample http = new HttpURLConnectionExample();System.out.println("Testing 1 - Send Http GET request");http.sendGet();System.out.println("\nTesting 2 - Send Http POST request");http.sendPost();}// HTTP GET requestprivate void sendGet() throws Exception {String url = "http://www.google.com/search?q=mkyong";URL obj = new URL(url);HttpURLConnection con = (HttpURLConnection) obj.openConnection();// optional default is GETcon.setRequestMethod("GET");//add request headercon.setRequestProperty("User-Agent", USER_AGENT);int responseCode = con.getResponseCode();System.out.println("\nSending 'GET' request to URL : " + url);System.out.println("Response Code : " + responseCode);BufferedReader in = new BufferedReader(        new InputStreamReader(con.getInputStream()));String inputLine;StringBuffer response = new StringBuffer();while ((inputLine = in.readLine()) != null) {response.append(inputLine);}in.close();//print resultSystem.out.println(response.toString());}// HTTP POST requestprivate void sendPost() throws Exception {String url = "https://selfsolve.apple.com/wcResults.do";URL obj = new URL(url);HttpsURLConnection con = (HttpsURLConnection) obj.openConnection();//add reuqest headercon.setRequestMethod("POST");con.setRequestProperty("User-Agent", USER_AGENT);con.setRequestProperty("Accept-Language", "en-US,en;q=0.5");String urlParameters = "sn=C02G8416DRJM&cn=&locale=&caller=&num=12345";// Send post requestcon.setDoOutput(true);DataOutputStream wr = new DataOutputStream(con.getOutputStream());wr.writeBytes(urlParameters);wr.flush();wr.close();int responseCode = con.getResponseCode();System.out.println("\nSending 'POST' request to URL : " + url);System.out.println("Post parameters : " + urlParameters);System.out.println("Response Code : " + responseCode);BufferedReader in = new BufferedReader(        new InputStreamReader(con.getInputStream()));String inputLine;StringBuffer response = new StringBuffer();while ((inputLine = in.readLine()) != null) {response.append(inputLine);}in.close();//print resultSystem.out.println(response.toString());}}

Output

Sending 'GET' request to URL : http://www.google.com/search?q=mkyongResponse Code : 200Google search result...Testing 2 - Send Http POST requestSending 'POST' request to URL : https://selfsolve.apple.com/wcResults.doPost parameters : sn=C02G8416DRJM&cn=&locale=&caller=&num=12345Response Code : 200Apple product detail...



2. Apache HttpClient

This is the equivalent example, but using Apache HttpClient to make HTTP GET/POST request.

HttpClientExample.java
package com.mkyong;import java.io.BufferedReader;import java.io.InputStreamReader;import java.util.ArrayList;import java.util.List;import org.apache.http.HttpResponse;import org.apache.http.NameValuePair;import org.apache.http.client.HttpClient;import org.apache.http.client.entity.UrlEncodedFormEntity;import org.apache.http.client.methods.HttpGet;import org.apache.http.client.methods.HttpPost;import org.apache.http.impl.client.DefaultHttpClient;import org.apache.http.message.BasicNameValuePair;public class HttpClientExample {private final String USER_AGENT = "Mozilla/5.0";public static void main(String[] args) throws Exception {HttpClientExample http = new HttpClientExample();System.out.println("Testing 1 - Send Http GET request");http.sendGet();System.out.println("\nTesting 2 - Send Http POST request");http.sendPost();}// HTTP GET requestprivate void sendGet() throws Exception {String url = "http://www.google.com/search?q=developer";HttpClient client = new DefaultHttpClient();HttpGet request = new HttpGet(url);// add request headerrequest.addHeader("User-Agent", USER_AGENT);HttpResponse response = client.execute(request);System.out.println("\nSending 'GET' request to URL : " + url);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());}// HTTP POST requestprivate void sendPost() throws Exception {String url = "https://selfsolve.apple.com/wcResults.do";HttpClient client = new DefaultHttpClient();HttpPost post = new HttpPost(url);// add headerpost.setHeader("User-Agent", USER_AGENT);List<NameValuePair> urlParameters = new ArrayList<NameValuePair>();urlParameters.add(new BasicNameValuePair("sn", "C02G8416DRJM"));urlParameters.add(new BasicNameValuePair("cn", ""));urlParameters.add(new BasicNameValuePair("locale", ""));urlParameters.add(new BasicNameValuePair("caller", ""));urlParameters.add(new BasicNameValuePair("num", "12345"));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());}}

0 0
原创粉丝点击