日韩性视频-久久久蜜桃-www中文字幕-在线中文字幕av-亚洲欧美一区二区三区四区-撸久久-香蕉视频一区-久久无码精品丰满人妻-国产高潮av-激情福利社-日韩av网址大全-国产精品久久999-日本五十路在线-性欧美在线-久久99精品波多结衣一区-男女午夜免费视频-黑人极品ⅴideos精品欧美棵-人人妻人人澡人人爽精品欧美一区-日韩一区在线看-欧美a级在线免费观看

歡迎訪問 生活随笔!

生活随笔

當(dāng)前位置: 首頁 > 编程资源 > 编程问答 >内容正文

编程问答

java client_java中HttpClient的使用

發(fā)布時間:2023/11/30 编程问答 33 豆豆
生活随笔 收集整理的這篇文章主要介紹了 java client_java中HttpClient的使用 小編覺得挺不錯的,現(xiàn)在分享給大家,幫大家做個參考.

HttpClient的使用步驟:

1、使用Apache的HttpClient發(fā)送GET和POST請求的步驟如下:

1. 使用幫助類HttpClients創(chuàng)建CloseableHttpClient對象.?2. 基于要發(fā)送的HTTP請求類型創(chuàng)建HttpGet或者HttpPost實例.

3. 使用addHeader方法添加請求頭部,諸如User-Agent, Accept-Encoding等參數(shù).

4. 對于POST請求,創(chuàng)建NameValuePair列表,并添加所有的表單參數(shù).然后把它填充進HttpPost實體.

5. 通過執(zhí)行此HttpGet或者HttpPost請求獲取CloseableHttpResponse實例

6. 從此CloseableHttpResponse實例中獲取狀態(tài)碼,錯誤信息,以及響應(yīng)頁面等等.

7. 最后關(guān)閉HttpClient資源.

2、使用HttpClient發(fā)送請求、接收響應(yīng)很簡單,一般需要如下幾步即可:

1.?創(chuàng)建HttpClient對象,HttpClients.createDefault()。

2.?創(chuàng)建請求方法的實例,并指定請求URL。如果需要發(fā)送GET請求,創(chuàng)建HttpGet對象;如果需要發(fā)送POST請求,創(chuàng)建HttpPost對象,HttpPost httpPost = new HttpPost(url)。

3.?如果需要發(fā)送請求參數(shù),可調(diào)用HttpGet、HttpPost共同的setParams(HetpParams params)方法來添加請求參數(shù);對于HttpPost對象而言,也可調(diào)用setEntity(HttpEntity entity)方法來設(shè)置請求參數(shù)。List valuePairs = new LinkedList();valuePairs.add(new BasicNameValuePair(entry.getKey(),entry.getValue()));httpPost.setEntity(formEntity)。

4.?調(diào)用HttpClient對象的execute(HttpUriRequest request)發(fā)送請求,該方法返回一個HttpResponse。

5.?調(diào)用HttpResponse的getAllHeaders()、getHeaders(String name)等方法可獲取服務(wù)器的響應(yīng)頭;調(diào)用HttpResponse的getEntity()方法可獲取HttpEntity對象,該對象包裝了服務(wù)器的響應(yīng)內(nèi)容。程序可通過該對象獲取服務(wù)器的響應(yīng)內(nèi)容。

6.?釋放連接。無論執(zhí)行方法是否成功,都必須釋放連接

httpClient實例:

實例一:

package http;

import java.io.IOException;

import java.io.UnsupportedEncodingException;

import java.util.HashMap;

import java.util.LinkedList;

import java.util.List;

import java.util.Map;

import java.util.Map.Entry;

import org.apache.commons.httpclient.HttpClient;

import org.apache.http.HttpEntity;

import org.apache.http.HttpResponse;

import org.apache.http.NameValuePair;

import org.apache.http.client.ClientProtocolException;

import org.apache.http.client.entity.UrlEncodedFormEntity;

import org.apache.http.client.methods.HttpPost;

import org.apache.http.message.BasicNameValuePair;

import org.apache.http.util.EntityUtils;

import org.apache.http.impl.client.HttpClients;

public class HttpTest {

public Boolean isRequestSuccessful(HttpResponse httpresponse){

return httpresponse.getStatusLine().getStatusCode()==200;

}

public String HttpPost(String param1,String param2,String url) throws Exception{

Map personMap = new HashMap();

personMap.put("param1",param1);

personMap.put("param1",param2);

List list = new LinkedList();

for(Entry entry:personMap.entrySet()){

list.add(new BasicNameValuePair(entry.getKey(),entry.getValue()));

}

HttpPost httpPost = new HttpPost(url);

UrlEncodedFormEntity formEntity = new UrlEncodedFormEntity(list,"utf-8");

httpPost.setEntity(formEntity);

HttpClient httpCient = HttpClients.CreatDefault();

HttpResponse httpresponse = null;

try{

httpresponse = httpClient.execute(httpPost);

HttpEntity httpEntity = httpresponse.getEntity();

String response = EntityUtils.toString(httpEntity, "utf-8");

return response;

}catch(ClientProtocolException e){

System.out.println("http請求失敗,uri{},exception{}");

}catch(IOException e){

System.out.println("http請求失敗,uri{},exception{}");

}

return null;

}

}

實例二:

package com.kingdee.opensys.common.util.http;

import java.io.IOException;

import java.util.concurrent.locks.Lock;

import java.util.concurrent.locks.ReentrantLock;

import org.apache.http.HttpEntity;

import org.apache.http.client.ClientProtocolException;

import org.apache.http.client.entity.GzipDecompressingEntity;

import org.apache.http.client.methods.CloseableHttpResponse;

import org.apache.http.client.methods.HttpRequestBase;

import org.apache.http.impl.client.CloseableHttpClient;

import org.apache.http.impl.client.HttpClientBuilder;

import org.apache.http.impl.conn.PoolingHttpClientConnectionManager;

import org.apache.http.util.EntityUtils;

import org.slf4j.Logger;

import org.slf4j.LoggerFactory;

public class HttpClientHelper {

private static Logger logger = LoggerFactory.getLogger(HttpClientHelper.class);

private static HttpClientHelper instance = null;

private static Lock lock = new ReentrantLock();

private static CloseableHttpClient httpClient;

public HttpClientHelper(){

instance = this;

}

public static HttpClientHelper getHttpClient(){

if(instance == null){

lock.lock();

try{

instance = new HttpClientHelper();

}catch(Exception e){

e.printStackTrace();

}finally{

lock.unlock();

}

}

return instance;

}

public void init(){

PoolingHttpClientConnectionManager pool = new PoolingHttpClientConnectionManager();

pool.setMaxTotal(500);

pool.setDefaultMaxPerRoute(50);

httpClient = HttpClientBuilder.create().setConnectionManager(pool).build();

}

public byte[] executeAndReturnByte(HttpRequestBase request) throws Exception{

HttpEntity entity = null;

CloseableHttpResponse response = null;

byte[] base = new byte[0];

if(request==null){

return base;

}

if(httpClient==null){

init();

}

if(httpClient==null){

logger.error("http獲取異常");

return base;

}

response = httpClient.execute(request);

entity = response.getEntity();

if(response.getStatusLine().getStatusCode()==200){

String encode = (""+response.getFirstHeader("Content-Encoding")).toLowerCase();

if(encode.indexOf("gzip")>0){

entity = new GzipDecompressingEntity(entity);

}

base = EntityUtils.toByteArray(entity);

}else{

logger.error(""+response.getStatusLine().getStatusCode());

}

EntityUtils.consumeQuietly(entity);

response.close();

httpClient.close();

return base;

}

public String execute(HttpRequestBase request) throws Exception{

byte[] base = executeAndReturnByte(request);

if(base==null){

return null;

}

String result = new String(base,"UTF-8");

return result;

}

}

package com.kingdee.opensys.common.util.http;

import java.io.UnsupportedEncodingException;

import java.util.Iterator;

import java.util.LinkedList;

import java.util.List;

import java.util.Map;

import org.apache.http.HttpEntity;

import org.apache.http.client.config.RequestConfig;

import org.apache.http.client.entity.UrlEncodedFormEntity;

import org.apache.http.client.methods.HttpPost;

import org.apache.http.entity.StringEntity;

import org.apache.http.message.BasicNameValuePair;

import javax.servlet.http.HttpServletRequest;

public class HttpHelper {

private static String UTF8 = "UTF-8";

private static RequestConfig requestConfig;

public static String post(Map header,Map params,String url) throws Exception{

HttpPost post = null;

post = new HttpPost(url);

if(header!=null){

for(String key:header.keySet()){

post.addHeader(key, header.get(key));

}

}

if(params!=null){

List list = new LinkedList();

post.setConfig(getRequestConfig());

for(String key:params.keySet()){

list.add(new BasicNameValuePair(key,params.get(key)));

}

UrlEncodedFormEntity entity = new UrlEncodedFormEntity(list,UTF8);

post.setEntity(entity);

}

return HttpClientHelper.getHttpClient().execute(post);

}

public static String post(Map header,String jsonObject,String url) throws Exception{

HttpPost post = null;

post = new HttpPost(url);

if(header!=null){

for(String key:header.keySet()){

post.addHeader(key, header.get(key));

}

}

if(jsonObject.isEmpty()){

throw new Exception("jsonObject不能為空!");

}

HttpEntity entity = new StringEntity(jsonObject,"UTF-8");

return HttpClientHelper.getHttpClient().execute(post);

}

public static String post(Map params,String url) throws Exception{

HttpPost post = null;

post = new HttpPost(url);

List list = new LinkedList();

post.setConfig(getRequestConfig());

for(String key:params.keySet()){

list.add(new BasicNameValuePair(key,params.get(key)));

}

UrlEncodedFormEntity entity = new UrlEncodedFormEntity(list,UTF8);

post.setEntity(entity);

return HttpClientHelper.getHttpClient().execute(post);

}

public static RequestConfig getRequestConfig(){

if(requestConfig==null){

requestConfig = RequestConfig.custom().setConnectionRequestTimeout(20000)

.setConnectTimeout(20000).setSocketTimeout(20000).build();

}

return requestConfig;

}

public static String getClientIp(HttpServletRequest request){

String ip = request.getHeader("x-forwarded-for");

if(ip==null||ip.length()==0||"unknown".equalsIgnoreCase(ip)){

ip = request.getHeader("Proxy-Client-IP");

}

if(ip==null||ip.length()==0||"unknown".equalsIgnoreCase(ip)){

ip = request.getHeader("WL-Proxy-Client_IP");

}

if(ip==null||ip.length()==0||"unkonwn".equalsIgnoreCase(ip)){

ip = request.getRemoteAddr();

}

if(ip.length()<5){

ip="0.0.0.0";

}

return ip;

}

}

總結(jié)

以上是生活随笔為你收集整理的java client_java中HttpClient的使用的全部內(nèi)容,希望文章能夠幫你解決所遇到的問題。

如果覺得生活随笔網(wǎng)站內(nèi)容還不錯,歡迎將生活随笔推薦給好友。