HttpClient用法

一个简单的  工具类使用HttpClinet

import java.io.BufferedInputStream;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.OutputStreamWriter;
import java.net.URL;
import java.net.URLConnection;
import java.util.HashMap;
import java.util.Map;

import javax.servlet.http.HttpServletRequest;

import net.sf.json.JSONObject;

import org.apache.commons.httpclient.HttpClient;
import org.apache.commons.httpclient.HttpMethod;
import org.apache.commons.httpclient.URIException;
import org.apache.commons.httpclient.methods.GetMethod;
import org.apache.commons.httpclient.methods.PostMethod;
import org.apache.commons.httpclient.methods.RequestEntity;
import org.apache.commons.httpclient.params.HttpMethodParams;
import org.apache.commons.httpclient.methods.StringRequestEntity; import org.apache.commons.httpclient.util.URIUtil; import org.apache.commons.lang.StringUtils; import org.apache.commons.logging.Log; import org.apache.commons.logging.LogFactory;

/** * HTTP工具箱 * **/ public final class HttpTookit { private static Log log = LogFactory.getLog(HttpTookit.class); /** * 执行一个HTTP GET请求,返回请求响应的HTML * * @param url 请求的URL地址 * @param queryString 请求的查询参数,可以为null * @return 返回请求响应的HTML */ public static String doGet(String url, String queryString) { String response = ""; HttpClient client = new HttpClient(); HttpMethod method = new GetMethod(url); try { if (StringUtils.isNotBlank(queryString)) //对get请求参数做了http请求默认编码,好像没有任何问题,汉字编码后,就成为%式样的字符串 method.setQueryString(URIUtil.encodeQuery(queryString)); client.executeMethod(method); response = new String(method.getResponseBody(),"utf-8"); } catch (URIException e) { log.error("执行HTTP Get请求时,编码查询字符串“" + queryString + "”发生异常!", e); } catch (IOException e) { log.error("执行HTTP Get请求" + url + "时,发生异常!", e); } finally { method.releaseConnection(); } return response; } /** * 执行一个HTTP POST请求,返回请求响应的HTML * * @param url 请求的URL地址 * @param params 请求的查询参数,可以为null * @return 返回请求响应的HTML */ public static String doPost(String url, Map<String, String> params) { String response = ""; HttpClient client = new HttpClient(); PostMethod method = new PostMethod(url); //设置Http Post数据 if (params != null) { for (Map.Entry<String, String> entry : params.entrySet()) { method.addParameter(entry.getKey(), entry.getValue()); } } try {
              method.getParams().setParameter(HttpMethodParams.HTTP_CONTENT_CHARSET, "UTF-8"); client.executeMethod(method); response
= new String(method.getResponseBody(),"utf-8"); } catch (IOException e) { log.error("执行HTTP Post请求" + url + "时,发生异常!", e); } finally { method.releaseConnection(); } return response; } /** * 返回post请求中的包内容 * @param request 请求 */ public static String getPostContent(HttpServletRequest request){ StringBuffer params = new StringBuffer(); InputStream in = null ; BufferedInputStream buf = null; try { in = request.getInputStream(); buf = new BufferedInputStream(in); byte[] buffer = new byte[1024]; int read; while((read=buf.read(buffer))!=-1){ params.append(new String(buffer,0,read,"UTF-8")); } } catch (IOException e) { e.printStackTrace(); }finally{ try { if(null!=in){ in.close(); } if(null!=buf){ buf.close(); } } catch (IOException e) { e.printStackTrace(); } } return params.toString(); }public static String doPostString(String url,String paramStr,String charset){ StringBuffer resultBuffer = null; URLConnection con = null; OutputStreamWriter osw = null; BufferedReader br = null; try { URL realUrl = new URL(url); // 打开和URL之间的连接 con = realUrl.openConnection(); // 设置通用的请求属性 con.setRequestProperty("accept", "*/*"); con.setRequestProperty("connection", "Keep-Alive"); con.setRequestProperty("Content-Type", "application/x-www-form-urlencoded"); con.setRequestProperty("user-agent", "Mozilla/4.0 (compatible; MSIE 6.0; Windows NT 5.1;SV1)"); // 发送POST请求必须设置如下两行 con.setDoOutput(true); con.setDoInput(true); // 获取URLConnection对象对应的输出流 osw = new OutputStreamWriter(con.getOutputStream(), charset); if (paramStr != null && paramStr.length() > 0) { // 发送请求参数 osw.write(paramStr.substring(0, paramStr.length() - 1)); // flush输出流的缓冲 osw.flush(); } // 定义BufferedReader输入流来读取URL的响应 resultBuffer = new StringBuffer(); int contentLength = Integer.parseInt(con.getHeaderField("Content-Length")); if (contentLength > 0) { br = new BufferedReader(new InputStreamReader(con.getInputStream(), charset)); String temp; while ((temp = br.readLine()) != null) { resultBuffer.append(temp); } } } catch (Exception e) { throw new RuntimeException(e); } finally { if (osw != null) { try { osw.close(); } catch (IOException e) { osw = null; throw new RuntimeException(e); } } if (br != null) { try { br.close(); } catch (IOException e) { br = null; throw new RuntimeException(e); } } } return resultBuffer.toString(); } public static String doPostJson(String url, String jsonString) { String response = ""; HttpClient client = new HttpClient(); PostMethod method = new PostMethod(url); try { RequestEntity requestEntity = new StringRequestEntity(jsonString, "application/json", "UTF-8"); method.setRequestEntity(requestEntity); client.executeMethod(method); response = new String(method.getResponseBody(),"utf-8"); } catch (IOException e) { log.error("执行HTTP Post请求" + url + "时,发生异常!", e); } finally { method.releaseConnection(); } return response; } public static String convertStreamToString(InputStream is) { StringBuilder sb1 = new StringBuilder(); byte[] bytes = new byte[4096]; int size = 0; try { while ((size = is.read(bytes)) > 0) { String str = new String(bytes, 0, size, "UTF-8"); sb1.append(str); } } catch (IOException e) { e.printStackTrace(); } finally { try { is.close(); } catch (IOException e) { e.printStackTrace(); } } return sb1.toString(); } }

1.doget用法

//前面一个就是 url,后面一个参数就是  查询的参数  xxx/xxx?queryString 中的queryString
HttpTookit.doGet("http://localhost:8080/xm/jkmc","text="+text+"&size="+size)

2.doPost用法

Map<String,String> map = new HashMap<>();
map.put("param1","param1");
map.put("param2","param2");
HttpTookit.doPost("url",map);

 

转载于:https://www.cnblogs.com/zwdx/p/8042934.html

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值