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
- Standard HttpURLConnection.
- Apache HttpClient library.
1. Java HttpURLConnection example
This example uses HttpURLConnection (http) and HttpsURLConnection (https) to
- Send an HTTP GET request to Google.com to get the search result.
- 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
- How to send HTTP request GET/POST in Java
- Send HTTP Request GET/POST In Java
- How to send HTTP request in java?
- How to use GET and POST methods in HTTP from a MIDlet
- How to use HttpWebRequest to send POST request to another web server?
- How to use HttpWebRequest to send POST request to another web server?
- How to switch from POST to GET in PHP CURL
- how to send raw data to printer in java
- How to send pull request on Git
- Get/Post in http
- how to use UrlConnection to post/get request with basic authorization?
- How to get request_id of previous request in a request set?
- JAVA HTTP GET/POST
- java HTTP GET POST
- Get Post Data From Http Request
- HTTP Request的Get、Post的区别
- HTTP Request的Get、Post的区别
- HTTP Request的Get、Post的区别
- IT老兵:在Google供职十年整,到底能学到啥?
- x86和x64下boost库安装与配置
- BZOJ 1070, 修车
- 技术人的职场晋升指南:如何从20万到50万,再跨越到100万?大咖说回放
- Git,Github和Gitlab简介和使用方法
- How to send HTTP request GET/POST in Java
- iOS基于JSPatch的热修复
- How to automate login a website – Java example
- Upload file to servlet without using HTML form
- 来CSDN必做功课:阅读 zhao4zhong1 和 sp1234
- empty运算符
- 技术人的小目标:10000小时理论落地,你就是大牛
- Upload files by sending multipart request programmatically
- 程序员简易成长指南:从菜鸟码农到架构师