專案一(一) HttpClient中的POST請求和GET請求
HttpClient中的POST請求和GET請求
一、HttpClient簡述
HttpClient是Apache Jakarta Common下的子專案,用來提供高效的、最新的、功能豐富的支援HTTP協議的客戶端程式設計工具包,並且它支援HTTP協議最新的版本和建議。HttpClient已經應用在很多的專案中,比如Apache Jakarta上很著名的另外兩個開源專案Cactus和HTMLUnit都使用了HttpClient。
裡面封裝所有的請qui引數和相關資訊。
二、請求步驟
HttpClient請求主要分為四大步驟即可完成
1、第一步:建立HttpClient物件
2、步驟二:建立請求的方法,指定url
3、步驟三:對請求引數進行編碼、設定。
4、步驟四:進行通訊並對返回的報文做處理
三、首先使用HttpClient必須已用相對應的包,在以下的案例中引用到了三個jar包
httpclient-4.3.3.jar
httpcore-4.3.2.jar
log4j-1.2.16.jar
commons-logging-1.0.4.jar
四、程式碼案例
package com.flx.dome1;
import java.io.IOException;
import java.security.KeyManagementException;
import java.security.KeyStoreException;
import java.security.NoSuchAlgorithmException;
import java.security.cert.CertificateException;
import java.security.cert.X509Certificate;
import java.util.Date;
import javax.net.ssl.SSLContext;
import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.HttpStatus;
import org.apache.http.client.ClientProtocolException;
import org.apache.http.client.HttpClient;
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.conn.ssl.SSLConnectionSocketFactory;
import org.apache.http.conn.ssl.SSLContextBuilder;
import org.apache.http.conn.ssl.TrustStrategy;
import org.apache.http.entity.StringEntity;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClients;
import org.apache.http.util.EntityUtils;
/**
*
* @author FuLX
*
*/
public class HttpTool {
/**
* 用https方式發出post請求
*
* @param url
* @param entity
* 要傳送的字串
* @return
*/
public static String httpPost(String url, String entity) {
if (url == null || url.length() == 0) {
return null;
}
//1、第一步:建立HttpClient物件
HttpClient httpClient = createSSLClientDefault();
//2、步驟二:建立請求的方法,指定url
HttpPost httpPost = new HttpPost(url);
httpPost.setHeader("Connection", "Close");
Date date1 = new Date();
System.out.println("url==" + url);
System.out.println("request==" + entity);
try {
//3、步驟三:對請求引數進行編碼、設定。
httpPost.setEntity(new StringEntity(new String(entity
.getBytes("UTF-8"), "ISO8859-1")));
httpPost.setHeader("Accept", "application/xml");
httpPost.setHeader("Content-type", "application/xml");
//4、步驟四:進行通訊並對返回的報文做處理
HttpResponse resp = httpClient.execute(httpPost);
if (resp.getStatusLine().getStatusCode() != HttpStatus.SC_OK) {
return null;
}
String res = EntityUtils.toString(resp.getEntity(), "UTF-8");
// if (log.isDebugEnabled()) {
Date date2 = new Date();
long l = date2.getTime() - date1.getTime();
System.out.println("time==" + l);
if (l > 10000) {
System.out.println("超過10秒==" + l);
}
System.out.println("response==" + res);
// }
return res;
} catch (Exception e) {
System.out.println("url==" + url);
System.out.println("request==" + entity);
e.printStackTrace();
throw new RuntimeException(e);
}
}
/**
* 用https方式發出get請求
*
* @param url
* @throws IOException
* @throws ClientProtocolException
*/
public static String sendRequest(String url) throws IOException,
ClientProtocolException {
CloseableHttpClient httpclient = createSSLClientDefault();
HttpGet httpget = new HttpGet(url);
// httpget.setHeader("Connection", "Close");
// System.out.println("executing request" + httpget.getRequestLine());
CloseableHttpResponse response = httpclient.execute(httpget);
try {
HttpEntity entity = response.getEntity();
// System.out.println("----------------------------------------");
// System.out.println(response.getStatusLine());
if (entity != null) {
// System.out.println("Response content length: "
// + entity.getContentLength());
}
String responseStr = EntityUtils.toString(entity, "UTF-8");
return responseStr;
} finally {
response.close();
}
}
public static CloseableHttpClient createSSLClientDefault() {
try {
SSLContext sslContext = new SSLContextBuilder().loadTrustMaterial(
null, new TrustStrategy() {
// 信任所有
public boolean isTrusted(X509Certificate[] chain,
String authType) throws CertificateException {
return true;
}
}).build();
SSLConnectionSocketFactory sslsf = new SSLConnectionSocketFactory(
sslContext);
return HttpClients.custom().setSSLSocketFactory(sslsf).build();
} catch (KeyManagementException e) {
e.printStackTrace();
} catch (NoSuchAlgorithmException e) {
e.printStackTrace();
} catch (KeyStoreException e) {
e.printStackTrace();
}
return HttpClients.createDefault();
}
public final static void main(String[] args) throws Exception {
String url="http://localhost:8080/SSO/access/joinup?requestSource=wapPay2&userCode=99C1C32FAA23027414AEF464A7AFEF0A41AE1FE7965E947D6CBAF4BED0495FA7&clientName=H007001&target=cx";
String requestStr="<request><cityMsg><cityCarNo>000000</cityCarNo><city>上海市</city></cityMsg><vehicle><ownerName>張三</ownerName><registerDate>1</registerDate><frameNo>2</frameNo><engineNo>3</engineNo><licInput>滬ATEST</licInput></vehicle></request>";
//post請求
String respsonsePost = HttpTool.httpPost(url, requestStr);
//get請求
String respsonseGet = HttpTool.sendRequest(url);
System.out.println("POST返回引數:" + respsonsePost);
System.out.println("GET返回引數:" + respsonseGet);
}
}
五、結果展示
POST返回引數:<response><head><status>S</status></head><body><url>http://b.test.com:8080/cxInterface/goSinopecJoin.do?ticket=56594999-7667-41b8-ad01-2bc9446349421489655631439</url></body></response>
GET返回引數:<response><head><status>S</status></head><body><url>http://b.test.com:8080/cxInterface/goSinopecJoin.do?ticket=d9a418f3-2cfd-4ce8-9a0f-2a14d5e09e0d1489655631517</url></body></response>
相關文章
- get請求和post請求的區別
- vue 發起get請求和post請求Vue
- uni-app的POST請求和GET請求APP
- get請求和post請求區別詳解
- Android Http請求框架一:Get 和 Post 請求AndroidHTTP框架
- iOS 同步請求 非同步請求 GET請求 POST請求iOS非同步
- SpringMVC中如何傳送GET請求、POST請求、PUT請求、DELETE請求。SpringMVCdelete
- 一個封裝的使用Apache HttpClient進行Http請求(GET、POST、PUT等)的類。封裝ApacheHTTPclient
- 使用HttpClient傳送GET請求HTTPclient
- JAVA中Get和Post請求的區別Java
- 都2020年了,還理不清GET請求和POST請求區別?
- get與post的請求區別
- POST與GET請求區別
- HTTP Get,Post請求詳解HTTP
- Get和Post請求詳解
- Android okHttp網路請求之Get/Post請求AndroidHTTP
- java apache commons HttpClient傳送get和post請求的學習整理JavaApacheHTTPclient
- http請求中get和post方法的區別HTTP
- HTTP協議中請求方法的Get和PostHTTP協議
- 【轉】怎麼用PHP傳送HTTP請求(POST請求、GET請求)?PHPHTTP
- Python中get、post請求詳解(HTTP請求頭、狀態碼)PythonHTTP
- 如何在Camel中Post一個請求?
- get和post請求的區別(面試)面試
- java傳送http的get、post請求JavaHTTP
- HttpUrlConnection和HttpClient和android-async-http框架的GET和POST請求HTTPclientAndroid框架
- java傳送GET和post請求Java
- go對get、post請求封裝Go封裝
- get,post URL加字尾請求
- PHP傳送POST和GET請求PHP
- Java Http Get Post 請求工具類JavaHTTP
- AJAX的POST和GET請求的區別
- http請求之get和post的區別HTTP
- ajax的post或者get伺服器請求伺服器
- 淺談HTTP中GET和POST請求方式的區別HTTP
- axios 發get,post 請求小結iOS
- httprequest- post- get -傳送請求HTTP
- php 利用socket傳送GET,POST請求PHP
- Http請求get與post請求方式的各種相關面試總結HTTP面試