项目一(一) HttpClient中的POST请求和GET请求

来源:互联网 发布:ides属于什么算法 编辑:程序博客网 时间:2024/06/06 02:31

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、步骤二:创建请求的方法,指定urlHttpPost 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>


0 0
原创粉丝点击