栏目分类:
子分类:
返回
名师互学网用户登录
快速导航关闭
当前搜索
当前分类
子分类
实用工具
热门搜索
名师互学网 > IT > 软件开发 > 后端开发 > Java

http请求 commons-httpclient(3.1)与httpclient(4.5.13)

Java 更新时间: 发布时间: IT归档 最新发布 模块sitemap 名妆网 法律咨询 聚返吧 英语巴士网 伯小乐 网商动力

http请求 commons-httpclient(3.1)与httpclient(4.5.13)

一、commons-httpclient(3.1)(已经不在维护了)



    commons-httpclient
    commons-httpclient
    3.1


    org.apache.httpcomponents
    httpcore
    4.4.14

commons-httpclient调用示例

import org.apache.commons.httpclient.HttpClient;
import org.apache.commons.httpclient.HttpException;
import org.apache.commons.httpclient.NameValuePair;
import org.apache.commons.httpclient.methods.PostMethod;
import org.apache.http.params.CoreConnectionPNames;

private static final String paramBody = "{"param": { "key": "" + key + "","secret": "" + secret + ""}}";


private static String getToken(String sign){
	//1.构造HttpClient的实例
	HttpClient httpClient = new HttpClient();
	httpClient.getParams().setContentCharset("utf-8");
	//设置连接超时:
	httpClient.getParams().setParameter(CoreConnectionPNames.CONNECTION_TIMEOUT, 3000);
	//设置读取超时:
	//httpClient.getParams().setParameter(CoreConnectionPNames.SO_TIMEOUT, 5000);

	//2.构造PostMethod的实例
	PostMethod postMethod = new PostMethod(url);
	//like12 add,20160511,中文转码 //在头文件中设置转码
	//postMethod.addRequestHeader("Content-Type", "application/x-www-form-urlencoded;charset=gbk");
	postMethod.addRequestHeader("Content-Type", "application/json;charset=utf-8");

	//3.0把参数放在Header中
	postMethod.addRequestHeader("apiCode", apiCode);
	postMethod.addRequestHeader("appId",appId);
	postMethod.addRequestHeader("requestNo",requestNo);
	postMethod.addRequestHeader("sign",sign);
	//3.把参数值放入到PostMethod对象中
	//方式1:
	//NameValuePair[] data = {
	//	new NameValuePair("param", "")
	//};
	//postMethod.setRequestBody(data);
	//方式2:
	postMethod.setRequestBody(paramBody);

	try {
		// 4.执行postMethod,调用http接口
		httpClient.executeMethod(postMethod);//200

		//5.读取内容
		//String responseMsg = postMethod.getResponseBodyAsString().trim();
		//########################################################//
		//解决报警告的问题WARN : org.apache.commons.httpclient.HttpMethodBase -
		//Going to buffer response body of large or unknown size.
		//Using getResponseBodyAsStream instead is recommended.
		InputStream is = postMethod.getResponseBodyAsStream();
        //like12 modified,20220530,解决中文乱码的问题
        //BufferedReader br = new BufferedReader(new InputStreamReader(is));
        BufferedReader br = new BufferedReader(new InputStreamReader(is, "UTF-8"));
		StringBuffer sb = new StringBuffer();
		String str= "";
		while((str = br.readLine()) != null){
			sb.append(str);
		}
		String responseMsg = sb.toString();
		//########################################################//
		System.out.println("responseMsg:" + responseMsg);

		//6.处理返回的内容
		return responseMsg;
	} catch (HttpException e) {
		e.printStackTrace();
	} catch (IOException e) {
		e.printStackTrace();
	} finally {
		//7.释放连接
		postMethod.releaseConnection();
	}

	return null;
}

二、httpclient(4.5.13)



    org.apache.httpcomponents
    httpclient
    4.5.13

httpclient调用示例

import org.apache.http.client.config.RequestConfig;
import org.apache.http.client.methods.CloseableHttpResponse;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.entity.StringEntity;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClientBuilder;
import org.apache.http.util.EntityUtils;

private static final String paramBody = "{"param": { "key": "" + key + "","secret": "" + secret + ""}}";


private static String getToken(String sign){
	CloseableHttpClient httpClient = HttpClientBuilder.create().build();
	HttpPost httpPost = new HttpPost(url);
	//超时配置
	RequestConfig config = RequestConfig.custom()
			.setConnectTimeout(3000)//连接超时时间
			.setConnectionRequestTimeout(3000)//连接请求超时时间
			.setSocketTimeout(5000)//socket读写超时时间
			.setCircularRedirectsAllowed(true)//设置是否允许重定向 默认为true
			.build();
	httpPost.setConfig(config);
	//设置header
	httpPost.setHeader("Content-type", "application/json;charset=utf-8");
	//把参数放在Header中
	httpPost.setHeader("apiCode", apiCode);
	httpPost.setHeader("appId", appId);
	httpPost.setHeader("requestNo", requestNo);
	httpPost.setHeader("sign", sign);
	//组织请求参数
	StringEntity stringEntity = new StringEntity(paramBody, "utf-8");
	httpPost.setEntity(stringEntity);

	//执行
	CloseableHttpResponse response = null;
	try {
		response = httpClient.execute(httpPost);
		return EntityUtils.toString(response.getEntity(), "utf-8");
	} catch (IOException e) {
		e.printStackTrace();
	} finally {
		try {
			if (null != response) {
				response.close();
			}
			if (null != httpClient) {
				httpClient.close();
			}
		} catch (IOException e) {
			e.printStackTrace();
		}
	}
	return null;
}

HttpClientUtil.java工具类

package com.qyj.utils;

import java.io.IOException;
import java.io.UnsupportedEncodingException;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import java.util.Set;

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.HttpDelete;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.client.methods.HttpPut;
import org.apache.http.entity.StringEntity;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClientBuilder;
import org.apache.http.message.BasicNameValuePair;
import org.apache.http.util.EntityUtils;

public class HttpClientUtil {
    
    public static String httpGet(String url, Map params) {
        CloseableHttpClient httpClient = HttpClientBuilder.create().build();
        //组织请求参数
        if (null != params && !params.isEmpty()) {
            StringBuilder stringBuilder = new StringBuilder(url);
            stringBuilder.append("?");
            for (Map.Entry entry : params.entrySet()) {
                stringBuilder.append(entry.getKey()).append("=")
                        .append(entry.getValue()).append("&");
            }
            url = stringBuilder.toString();
        }
        HttpGet httpGet = new HttpGet(url);
        //超时配置
        RequestConfig config = RequestConfig.custom()
                .setConnectTimeout(3000)//连接超时时间
                .setConnectionRequestTimeout(3000)//连接请求超时时间
                .setSocketTimeout(5000)//socket读写超时时间
                .setCircularRedirectsAllowed(true)//设置是否允许重定向 默认为true
                .build();
        httpGet.setConfig(config);

        //执行
        CloseableHttpResponse response = null;
        try {
            response = httpClient.execute(httpGet);
            return EntityUtils.toString(response.getEntity(), "utf-8");
        } catch (IOException e) {
            e.printStackTrace();
        } finally {
            try {
                if (response != null) {
                    response.close();
                }
                if (httpClient != null) {
                    httpClient.close();
                }
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
        return null;
    }

    
    public static String httpPost(String url, String jsonStr) {
        CloseableHttpClient httpClient = HttpClientBuilder.create().build();
        HttpPost httpPost = new HttpPost(url);
        //超时配置
        RequestConfig config = RequestConfig.custom()
                .setConnectTimeout(3000)//连接超时时间
                .setConnectionRequestTimeout(3000)//连接请求超时时间
                .setSocketTimeout(5000)//socket读写超时时间
                .setCircularRedirectsAllowed(true)//设置是否允许重定向 默认为true
                .build();
        httpPost.setConfig(config);
        //如果接受端是json形式,必须指定Content-Type为json
        httpPost.setHeader("Content-Type", "application/json;charset=utf8");
        StringEntity stringEntity = new StringEntity(jsonStr, "utf-8");
        httpPost.setEntity(stringEntity);

        //执行
        CloseableHttpResponse response = null;
        try {
            response = httpClient.execute(httpPost);
            return EntityUtils.toString(response.getEntity(), "utf-8");
        } catch (IOException e) {
            e.printStackTrace();
        } finally {
            try {
                if (null != response) {
                    response.close();
                }
                if (null != httpClient) {
                    httpClient.close();
                }
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
        return null;
    }

    //###################################################################//
    
    public static String httpGetHeader(String url, Map headers){
        CloseableHttpClient httpClient = HttpClientBuilder.create().build();
        HttpGet httpGet = new HttpGet(url);
        //超时配置
        RequestConfig config = RequestConfig.custom()
                .setConnectTimeout(3000)//连接超时时间
                .setConnectionRequestTimeout(3000)//连接请求超时时间
                .setSocketTimeout(5000)//socket读写超时时间
                .setCircularRedirectsAllowed(true)//设置是否允许重定向 默认为true
                .build();
        httpGet.setConfig(config);
        //设置header
        if (headers != null && headers.size() > 0) {
            for (Map.Entry entry : headers.entrySet()) {
                httpGet.setHeader(entry.getKey(),entry.getValue());
            }
        }

        //执行
        CloseableHttpResponse response = null;
        try {
            response = httpClient.execute(httpGet);
            return EntityUtils.toString(response.getEntity(), "utf-8");
        } catch (IOException e) {
            e.printStackTrace();
        } finally {
            try {
                if (null != response) {
                    response.close();
                }
                if (null != httpClient) {
                    httpClient.close();
                }
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
        return null;
    }

    
    public static String httpPostParam(String url, Map headers, Map params){
        CloseableHttpClient httpClient = HttpClientBuilder.create().build();
        HttpPost httpPost = new HttpPost(url);
        //超时配置
        RequestConfig config = RequestConfig.custom()
                .setConnectTimeout(3000)//连接超时时间
                .setConnectionRequestTimeout(3000)//连接请求超时时间
                .setSocketTimeout(5000)//socket读写超时时间
                .setCircularRedirectsAllowed(true)//设置是否允许重定向 默认为true
                .build();
        httpPost.setConfig(config);
        //设置header
        if (headers != null && headers.size() > 0) {
            for (Map.Entry entry : headers.entrySet()) {
                httpPost.setHeader(entry.getKey(),entry.getValue());
            }
        }
        //组织请求参数  
        List paramList = new ArrayList ();
        if(params != null && params.size() > 0){
            Set keySet = params.keySet();
            for(String key : keySet) {
                paramList.add(new BasicNameValuePair(key, params.get(key)));
            }
        }
        try {
            httpPost.setEntity(new UrlEncodedFormEntity(paramList, "utf-8"));
        } catch (UnsupportedEncodingException e1) {
            e1.printStackTrace();
        }

        //执行
        CloseableHttpResponse response = null;
        try {
            response = httpClient.execute(httpPost);
            return EntityUtils.toString(response.getEntity(), "utf-8");
        } catch (IOException e) {
            e.printStackTrace();
        } finally {
            try {
                if (null != response) {
                    response.close();
                }
                if (null != httpClient) {
                    httpClient.close();
                }
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
        return null;
    }

    
    public static String httpPostRaw(String url, Map headers, String jsonStr){
        CloseableHttpClient httpClient = HttpClientBuilder.create().build();
        HttpPost httpPost = new HttpPost(url);
        //超时配置
        RequestConfig config = RequestConfig.custom()
                .setConnectTimeout(3000)//连接超时时间
                .setConnectionRequestTimeout(3000)//连接请求超时时间
                .setSocketTimeout(5000)//socket读写超时时间
                .setCircularRedirectsAllowed(true)//设置是否允许重定向 默认为true
                .build();
        httpPost.setConfig(config);
        //设置header
        httpPost.setHeader("Content-type", "application/json");
        if (headers != null && headers.size() > 0) {
            for (Map.Entry entry : headers.entrySet()) {
                httpPost.setHeader(entry.getKey(),entry.getValue());
            }
        }
        //组织请求参数  
        StringEntity stringEntity = new StringEntity(jsonStr, "utf-8");
        httpPost.setEntity(stringEntity);

        //执行
        CloseableHttpResponse response = null;
        try {
            response = httpClient.execute(httpPost);
            return EntityUtils.toString(response.getEntity(), "utf-8");
        } catch (IOException e) {
            e.printStackTrace();
        } finally {
            try {
                if (null != response) {
                    response.close();
                }
                if (null != httpClient) {
                    httpClient.close();
                }
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
        return null;
    }

    
    public static String httpPutRaw(String url, Map headers, String jsonStr){
        CloseableHttpClient httpClient = HttpClientBuilder.create().build();
        HttpPut httpPut = new HttpPut(url);
        //超时配置
        RequestConfig config = RequestConfig.custom()
                .setConnectTimeout(3000)//连接超时时间
                .setConnectionRequestTimeout(3000)//连接请求超时时间
                .setSocketTimeout(5000)//socket读写超时时间
                .setCircularRedirectsAllowed(true)//设置是否允许重定向 默认为true
                .build();
        httpPut.setConfig(config);
        //设置header
        httpPut.setHeader("Content-type", "application/json");
        if (headers != null && headers.size() > 0) {
            for (Map.Entry entry : headers.entrySet()) {
                httpPut.setHeader(entry.getKey(),entry.getValue());
            }
        }
        //组织请求参数  
        StringEntity stringEntity = new StringEntity(jsonStr, "utf-8");
        httpPut.setEntity(stringEntity);

        //执行
        CloseableHttpResponse response = null;
        try {
            response = httpClient.execute(httpPut);
            return EntityUtils.toString(response.getEntity(), "utf-8");
        } catch (IOException e) {
            e.printStackTrace();
        } finally {
            try {
                if (null != response) {
                    response.close();
                }
                if (null != httpClient) {
                    httpClient.close();
                }
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
        return null;
    }

    
    public static String httpDelete(String url, Map headers){
        CloseableHttpClient httpClient = HttpClientBuilder.create().build();
        HttpDelete httpDelete = new HttpDelete(url);
        //超时配置
        RequestConfig config = RequestConfig.custom()
                .setConnectTimeout(3000)//连接超时时间
                .setConnectionRequestTimeout(3000)//连接请求超时时间
                .setSocketTimeout(5000)//socket读写超时时间
                .setCircularRedirectsAllowed(true)//设置是否允许重定向 默认为true
                .build();
        httpDelete.setConfig(config);
        //设置header
        if (headers != null && headers.size() > 0) {
            for (Map.Entry entry : headers.entrySet()) {
                httpDelete.setHeader(entry.getKey(),entry.getValue());
            }
        }

        //执行
        CloseableHttpResponse response = null;
        try {
            response = httpClient.execute(httpDelete);
            return EntityUtils.toString(response.getEntity(), "utf-8");
        } catch (IOException e) {
            e.printStackTrace();
        } finally {
            try {
                if (null != response) {
                    response.close();
                }
                if (null != httpClient) {
                    httpClient.close();
                }
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
        return null;
    }
    //###################################################################//
}

参考:

commons-httpclient与httpclient工具包 - 简书

使用HttpClient 发送 GET、POST(FormData、Raw)、PUT、Delete请求及文件上传 - 走看看

转载请注明:文章转载自 www.mshxw.com
本文地址:https://www.mshxw.com/it/936278.html
我们一直用心在做
关于我们 文章归档 网站地图 联系我们

版权所有 (c)2021-2022 MSHXW.COM

ICP备案号:晋ICP备2021003244-6号