使用HTTP協(xié)議發(fā)送GET/POST請求顿天,可以有多種方式,以下詳細介紹兩種方法。
一、JDK 的 java.net 包中提供的訪問 HTTP 協(xié)議功能發(fā)送GET/POST請求
1但惶、發(fā)送get請求詳細步驟
1)創(chuàng)建要請求的URL實例
String urlNameString = url + "?" + param;
URL realUrl = new URL(urlNameString);
2)打開和實例URL的連接
URLConnection connection = realUrl.openConnection();
3)為已打開的連接設置HTTP請求通用的屬性,如accept,connection,user-agent.
connection.setRequestProperty("accept", "*/*");
connection.setRequestProperty("connection", "Keep-Alive");
connection.setRequestProperty("user-agent",
"Mozilla/4.0 (compatible; MSIE 6.0; Windows NT 5.1;SV1)");
4)在設置好屬性的連接基礎上,執(zhí)行實際的連接,即發(fā)送請求
connection.connect();
5)獲取get請求的響應頭
Map<String, List<String>> map = connection.getHeaderFields();
// 遍歷所有的響應頭字段
for (String key : map.keySet()) {
System.out.println(key + "--->" + map.get(key));
}
6)獲取get請求的響應結(jié)果.這里可以通過BufferedReader輸入流來讀取URL的響應
BufferedReader in = new BufferedReader(new InputStreamReader(
connection.getInputStream()));
String line;
while ((line = in.readLine()) != null) {
result += line;
}
也可以使用工具類IOUtils的toString方法獲取響應結(jié)果.
result = IOUtils.toString(connection.getInputStream(),"utf-8");
7)關(guān)閉流,關(guān)閉連接
// 使用finally塊來關(guān)閉輸入流
finally {
try {
if (in != null) {
in.close();
}
} catch (Exception e2) {
e2.printStackTrace();
}
}
2、發(fā)送post請求詳細步驟
1)創(chuàng)建要請求的URL實例
String urlNameString = url + "?" + param;
URL realUrl = new URL(urlNameString);
2)打開和實例URL的連接
URLConnection connection = realUrl.openConnection();
3)為已打開的連接設置HTTP請求通用的屬性,如accept,connection,user-agent.
connection.setRequestProperty("accept", "*/*");
connection.setRequestProperty("connection", "Keep-Alive");
connection.setRequestProperty("user-agent",
"Mozilla/4.0 (compatible; MSIE 6.0; Windows NT 5.1;SV1)");
4)由于post請求,參數(shù)是放在body中,需要設置連接中允許寫入?yún)?shù)
conn.setDoOutput(true);
conn.setDoInput(true);
5)獲取URLConnection對象對應的輸出流
PrintWriter out = new PrintWriter(conn.getOutputStream());
6)寫入發(fā)送post請求需要的參數(shù)
out.print(param);
out.flush();
6)獲取get請求的響應結(jié)果.這里可以通過BufferedReader輸入流來讀取URL的響應
BufferedReader in = new BufferedReader(new InputStreamReader(
connection.getInputStream()));
String line;
while ((line = in.readLine()) != null) {
result += line;
}
也可以使用工具類IOUtils的toString方法獲取響應結(jié)果.
List<String> list = IOUtils.readLines(conn.getInputStream(),"UTF-8");
for(String s:list){
System.out.println(s);
}
7)關(guān)閉流,關(guān)閉連接
完整代碼:
package com.sc.http;
import org.apache.commons.io.IOUtils;
import java.io.BufferedReader;
import java.io.InputStreamReader;
import java.io.PrintWriter;
import java.net.URL;
import java.net.URLConnection;
import java.util.List;
import java.util.Map;
public class HttpRequest {
/**
* 向指定URL發(fā)送GET方法的請求
*
* @param url
* 發(fā)送請求的URL
* @param param
* 請求參數(shù)湿蛔,請求參數(shù)應該是 name1=value1&name2=value2 的形式膀曾。
* @return URL 所代表遠程資源的響應結(jié)果
*/
public static String sendGet(String url, String param) {
String result = "";
BufferedReader in = null;
try {
String urlNameString = url + "?" + param;
URL realUrl = new URL(urlNameString);
// 打開和URL之間的連接
URLConnection connection = realUrl.openConnection();
// 設置通用的請求屬性
connection.setRequestProperty("accept", "*/*");
connection.setRequestProperty("connection", "Keep-Alive");
connection.setRequestProperty("user-agent",
"Mozilla/4.0 (compatible; MSIE 6.0; Windows NT 5.1;SV1)");
// 建立實際的連接
connection.connect();
// 獲取所有響應頭字段
Map<String, List<String>> map = connection.getHeaderFields();
// 遍歷所有的響應頭字段
for (String key : map.keySet()) {
System.out.println(key + "--->" + map.get(key));
}
//定義 BufferedReader輸入流來讀取URL的響應
in = new BufferedReader(new InputStreamReader(
connection.getInputStream()));
String line;
while ((line = in.readLine()) != null) {
result += line;
}
result = IOUtils.toString(connection.getInputStream(),"utf-8");
} catch (Exception e) {
System.out.println("發(fā)送GET請求出現(xiàn)異常!" + e);
e.printStackTrace();
}
// 使用finally塊來關(guān)閉輸入流
finally {
try {
if (in != null) {
in.close();
}
} catch (Exception e2) {
e2.printStackTrace();
}
}
return result;
}
/**
* 向指定 URL 發(fā)送POST方法的請求
*
* @param url
* 發(fā)送請求的 URL
* @param param
* 請求參數(shù)阳啥,請求參數(shù)應該是 name1=value1&name2=value2 的形式添谊。
* @return 所代表遠程資源的響應結(jié)果
*/
public static String sendPost(String url, String param) {
PrintWriter out = null;
BufferedReader in = null;
String result = "";
try {
URL realUrl = new URL(url);
// 打開和URL之間的連接
URLConnection conn = realUrl.openConnection();
// 設置通用的請求屬性
conn.setRequestProperty("accept", "*/*");
conn.setRequestProperty("connection", "Keep-Alive");
conn.setRequestProperty("user-agent",
"Mozilla/4.0 (compatible; MSIE 6.0; Windows NT 5.1;SV1)");
// 發(fā)送POST請求必須設置如下兩行
conn.setDoOutput(true);
conn.setDoInput(true);
// 獲取URLConnection對象對應的輸出流
out = new PrintWriter(conn.getOutputStream());
// 發(fā)送請求參數(shù)
out.print(param);
// flush輸出流的緩沖
out.flush();
// 定義BufferedReader輸入流來讀取URL的響應
in = new BufferedReader(
new InputStreamReader(conn.getInputStream()));
String line;
while ((line = in.readLine()) != null) {
result += line;
}
// List<String> list = IOUtils.readLines(conn.getInputStream(),"UTF-8");
// for(String s:list){
// System.out.println(s);
// }
} catch (Exception e) {
System.out.println("發(fā)送 POST 請求出現(xiàn)異常!"+e);
e.printStackTrace();
}
//使用finally塊來關(guān)閉輸出流苫纤、輸入流
finally{
try{
if(out!=null){
out.close();
}
if(in!=null){
in.close();
}
}
catch(Exception ex){
ex.printStackTrace();
}
}
return result;
}
public static void main(String[] args) {
//發(fā)送 GET 請求
// String s=HttpRequest.sendGet("http://www.baidu.com", "key=123&v=456");
// System.out.println(s);
//發(fā)送 POST 請求
String sr=HttpRequest.sendPost("http://192.168.200.66/zabbix/screens.php", "ddreset=1");
System.out.println(sr);
}
}
二、使用org.apache.http包下的HttpClient發(fā)送GET/POST請求
HttpClient相比傳統(tǒng)JDK自帶的URLConnection,增加了易用性和靈活性卷拘。它不僅是客戶端發(fā)送Http請求變得容易喊废,而且也方便了開發(fā)人員測試接口(基于Http協(xié)議的),即提高了開發(fā)的效率栗弟,也方便提高代碼的健壯性污筷。
1、HttpClient發(fā)送get請求(無參數(shù))詳細步驟
1). 創(chuàng)建HttpClient對象
CloseableHttpClient httpclient = HttpClients.createDefault();
2). 創(chuàng)建請求方法的實例乍赫,并指定請求URL
HttpGet get = new HttpGet("http://www.baidu.com");
3). 調(diào)用HttpClient對象的execute(HttpUriRequest request)發(fā)送請求瓣蛀,該方法返回一個HttpResponse。
CloseableHttpResponse response= httpclient.execute(get);
4).獲取get請求的響應結(jié)果.調(diào)用HttpResponse的getEntity()方法可獲取HttpEntity對象雷厂,該對象包裝了服務器的響應內(nèi)容
HttpEntity entity = response.getEntity();
獲取響應狀態(tài)
int code = response.getStatusLine().getStatusCode();
System.out.println(" code "+code);
5).通過BufferedReader輸入流讀取響應結(jié)果
BufferedReader in = new BufferedReader(
new InputStreamReader(entity.getContent(),"UTF-8"));
String line;
String result="";
while ((line = in.readLine()) != null) {
result += line+"\n";
}
System.out.println(result);
可以使用工具類IOUtils的toString方法獲取響應結(jié)果.
List<String> list = IOUtils.readLines(entity.getContent(),"UTF-8");
for(String s:list){
System.out.println(s);
}
或者:
result=IOUtils.toString(entity.getContent(),"utf-8");
可以使用EntityUtils的toString方法獲取響應結(jié)果.(推薦使用)
if(entity!=null){
System.out.println(EntityUtils.toString(entity));
}
6).釋放連接,無論執(zhí)行方法是否成功惋增,都必須釋放連接
完整代碼:
package com.sc.http;
import java.io.IOException;
import org.apache.http.HttpEntity;
import org.apache.http.client.ClientProtocolException;
import org.apache.http.client.methods.CloseableHttpResponse;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClients;
import org.apache.http.util.EntityUtils;
public class HttpClientTest2 {
public static void main(String[] args) {
CloseableHttpClient httpclient = HttpClients.createDefault();
CloseableHttpResponse response = null;
HttpEntity entity=null;
try {
HttpGet get = new HttpGet("http://www.baidu.com");
response = httpclient.execute(get);
entity = response.getEntity();
int code = response.getStatusLine().getStatusCode();
System.out.println(" code "+code);
if(entity!=null){
System.out.println(EntityUtils.toString(entity));
}
} catch (ClientProtocolException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}finally {
try {
EntityUtils.consume(entity);
httpclient.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
}
2、HttpClient發(fā)送post請求詳細步驟
1). 創(chuàng)建HttpClient對象
CloseableHttpClient httpclient = HttpClients.createDefault();
2). 創(chuàng)建請求方法的實例改鲫,并指定請求URL
HttpPost post = new HttpPost("http://123.58.251.183:8080/goods/UserServlet");
3). 創(chuàng)建HttpEntity,模擬一個表單,用于包裝參數(shù)
POST請求,參數(shù)是放在body內(nèi),所以需要構(gòu)建UrlEncodedFormEntity
而UrlEncodedFormEntity需要傳入的參數(shù)類型為List且List中裝入的是NameValuePair類型的集合
NameValuePair是一個接口,它的實現(xiàn)類是BasicNameValuePair
BasicNameValuePair類的構(gòu)造方法中需要傳入兩個參數(shù)key,value
List<NameValuePair> list = new ArrayList<NameValuePair>();
list.add(new BasicNameValuePair("method","loginMobile"));
list.add(new BasicNameValuePair("loginname","abc"));
list.add(new BasicNameValuePair("loginpass","abc"));
HttpEntity postEntity = new UrlEncodedFormEntity(list);
post.setEntity(postEntity);
4). 若需要使用例如Fidder工具抓包,就需要設置代理.(無需抓包時,可省略此步)
HttpHost proxy = new HttpHost("127.0.0.1", 8888, "http");
RequestConfig config = RequestConfig.custom().setProxy(proxy).build();
post.setConfig(config);
5). 調(diào)用HttpClient對象的execute(HttpUriRequest request)發(fā)送請求诈皿,該方法返回一個HttpResponse。
CloseableHttpResponse response= httpclient.execute(get);
6).獲取get請求的響應結(jié)果.調(diào)用HttpResponse的getEntity()方法可獲取HttpEntity對象像棘,該對象包裝了服務器的響應內(nèi)容
HttpEntity entity = response.getEntity();
獲取響應狀態(tài)
int code = response.getStatusLine().getStatusCode();
System.out.println(" code "+code);
7).通過BufferedReader輸入流讀取響應結(jié)果
BufferedReader in = new BufferedReader(
new InputStreamReader(entity.getContent(),"UTF-8"));
String line;
String result="";
while ((line = in.readLine()) != null) {
result += line+"\n";
}
System.out.println(result);
可以使用工具類IOUtils的toString方法獲取響應結(jié)果.
List<String> list = IOUtils.readLines(entity.getContent(),"UTF-8");
for(String s:list){
System.out.println(s);
}
或者:
result=IOUtils.toString(entity.getContent(),"utf-8");
可以使用EntityUtils的toString方法獲取響應結(jié)果.(推薦使用)
if(entity!=null){
System.out.println(EntityUtils.toString(entity));
}
8).釋放連接,無論執(zhí)行方法是否成功稽亏,都必須釋放連接
EntityUtils.consume(httpEntity);
closeableHttpClient.close();
完整代碼:
package com.sc.http;
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;
import org.apache.http.HttpEntity;
import org.apache.http.HttpHost;
import org.apache.http.NameValuePair;
import org.apache.http.client.config.RequestConfig;
import org.apache.http.client.entity.UrlEncodedFormEntity;
import org.apache.http.client.methods.CloseableHttpResponse;
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;
public class HttpClientTest3 {
public static void main(String[] args) {
CloseableHttpClient closeableHttpClient = HttpClients.createDefault();
HttpPost post = new HttpPost("http://123.58.251.183:8080/goods/UserServlet");
List<NameValuePair> list = new ArrayList<NameValuePair>();
list.add(new BasicNameValuePair("method","loginMobile"));
list.add(new BasicNameValuePair("loginname","abc"));
list.add(new BasicNameValuePair("loginpass","abc"));
HttpHost proxy = new HttpHost("127.0.0.1", 8888, "http");
RequestConfig config = RequestConfig.custom().setProxy(proxy).build();
HttpEntity httpEntity = null;
try {
HttpEntity postEntity = new UrlEncodedFormEntity(list);
post.setEntity(postEntity);
//post.setConfig(config);
CloseableHttpResponse reponse = closeableHttpClient.execute(post);
httpEntity= reponse.getEntity();
System.out.println(EntityUtils.toString(httpEntity, "utf-8"));
} catch (IOException e) {
e.printStackTrace();
}finally {
try {
EntityUtils.consume(httpEntity);
closeableHttpClient.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
}