項目開發中經常存在各個服務間相互調用。比如我們開發的是服務端提供方,但是我們也會去訪問其他內部系統服務獲取想要的數據返回給調用我們服務的消費者。爲了便於學習,我重新整理了HttpClient。
HttpClient這個類的jar包是commons.httpclient-3.1.jar這個jar包是依賴了httpcore,commons-logging,commons-codec這三個jar包
commons-httpclient不在更新和維護了,建議使用org.apache.http.client.HttpClient,依賴jar包httpclient.jar。
但是一些老的項目中還是在用commons-httpclient。
所以首先整理一下org.apache.commons.httpclient.HttpClient類的常用使用方式,主要介紹一下get 和post一些常見的訪問調用方式。
一、DOGET方式
1、第一種方式
http://127.0.0.1:8080/SpringMvcService/dogetserver1?MulStr=tttt
注意特殊字符處理
2、第二種方式使用setQueryString方法,注意編碼格式
httpMethod.setQueryString(URIUtil.encodeQuery(resquest,charset));
package com.client.Utils;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.UnsupportedEncodingException;
import java.net.URLEncoder;
import java.nio.charset.Charset;
import org.apache.commons.httpclient.DefaultHttpMethodRetryHandler;
import org.apache.commons.httpclient.HttpClient;
import org.apache.commons.httpclient.HttpMethod;
import org.apache.commons.httpclient.HttpStatus;
import org.apache.commons.httpclient.methods.GetMethod;
import org.apache.commons.httpclient.params.HttpConnectionManagerParams;
import org.apache.commons.httpclient.params.HttpMethodParams;
import org.apache.commons.httpclient.util.URIUtil;
import org.apache.commons.lang.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.util.StreamUtils;
/**
* ClientUtilsByGet get方式實際開發不常用
* @author Administrator
*
*/
public class ClientUtilsByGet{
private static final Logger logger = LoggerFactory.getLogger(ClientUtilsByGet.class);
/**
* 執行一個帶參數的HTTP GET請求,返回請求響應的JSON字符串
*
* @param url 請求的URL地址
* @param param 請求參數 可以不傳
* @return 返回請求響應的JSON字符串
* @throws UnsupportedEncodingException
*/
public static String doGet(String url,String param) throws UnsupportedEncodingException {
String headerName=null;
String Response=null;
// 構造HttpClient的實例
HttpClient client = new HttpClient();
//設置參數
if(StringUtils.isNotBlank(param)) {
url=url+"?"+param;
}
// 創建GET方法的實例
GetMethod method = new GetMethod(url );
// 使用系統提供的默認的恢復策略
method.getParams().setParameter(HttpMethodParams.RETRY_HANDLER,new DefaultHttpMethodRetryHandler());
try {
// 執行getMethod
client.executeMethod(method);
System.out.println("返回的狀態碼爲:" +method.getStatusCode());
if (method.getStatusCode() == HttpStatus.SC_OK) {
Response=StreamUtils.copyToString(method.getResponseBodyAsStream(), Charset.forName("utf-8"));
}
} catch (IOException e) {
logger.error("執行HTTP Get請求" + url + "時,發生異常!", e);
return Response;
} finally {
method.releaseConnection();
}
return Response;
}
/**
* 執行一個HTTP GET請求,返回請求響應的HTML
*
* @param url 請求的URL地址
* @param queryString 請求的查詢參數,可以爲null
* @param charset 字符集
* @param pretty 是否美化
* @return 返回請求響應的HTML
*/
public static String DogetBystr(String url,String resquest, String charset, boolean pretty) {
StringBuffer response=new StringBuffer();
HttpClient httpClient=new HttpClient();
GetMethod httpMethod=new GetMethod(url);
HttpConnectionManagerParams httpConnectionManagerParams=httpClient.getHttpConnectionManager().getParams();
// 設置連接的超時時間
httpConnectionManagerParams.setConnectionTimeout(300000);
// 設置讀取數據的超時時間
httpConnectionManagerParams.setSoTimeout(300000);
try {
if(StringUtils.isNotBlank(resquest)) {
httpMethod.setQueryString(URIUtil.encodeQuery(resquest,charset));
}
httpClient.executeMethod(httpMethod);
System.out.println("返回的狀態碼爲:" +httpMethod.getStatusCode());
BufferedReader reader = new BufferedReader(new InputStreamReader(httpMethod.getResponseBodyAsStream(), charset));
String line;
while ((line = reader.readLine()) != null) {
if (pretty) {
response.append(line).append(System.getProperty("line.separator"));
} else {
response.append(line);
}
}
reader.close();
} catch (Exception e) {
logger.error("執行HTTP Get請求" + url + "時,發生異常!" + e);
return response.toString();
}
finally {
httpMethod.releaseConnection();
}
logger.info("http的請求地址爲:" + url + ",返回的狀態碼爲" + httpMethod.getStatusCode());
return response.toString();
}
}
調用主程序:
package com.client.test;
import java.io.UnsupportedEncodingException;
import java.util.HashMap;
import java.util.Map;
import org.apache.commons.httpclient.URI;
import org.apache.commons.httpclient.URIException;
import org.apache.commons.httpclient.methods.multipart.Part;
import org.apache.commons.httpclient.methods.multipart.StringPart;
import com.alibaba.fastjson.JSONObject;
import com.client.Utils.ClientUtilsByGet;
import com.client.Utils.ClientUtilsByPost;
/**
* Hello world!
*
*/
public class ClientTest
{
public static void main( String[] args ) throws URIException, NullPointerException
{
// String url="http://127.0.0.1:8081/SpringMvcService/dogetserver2?MulStr=111";
// URI u= new URI(url, true, "utf-8");
// System.out.println(urlbyget());
// System.out.println(urlbyget2());
}
public static String urlbyget() {
String url="http://127.0.0.1:8081/SpringMvcService/dogetserver1";
String contentType="application/json";
String charset="UTF-8";
String req="MulStr=tttt";
String resp="";
/*doGet*/
try {
resp=ClientUtilsByGet.doGet(url,req);
} catch (UnsupportedEncodingException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
return resp;
}
public static String urlbyget2() {
String url="http://127.0.0.1:8081/SpringMvcService/dogetserver1";
String reqStr=null;
String contentType="application/json";
String charset="UTF-8";
String resp=null;
Map<String, Object> map= new HashMap<String, Object>();
map.put("name", "liqiaorui");
map.put("age", "25");
JSONObject jsonObject=new JSONObject(map);
reqStr=jsonObject.toJSONString();
System.out.println("發送報文:"+reqStr);
resp=ClientUtilsByGet.DogetBystr(url, reqStr, charset,false);
System.out.println("返回報文:"+resp);
return resp;
}
}
服務端使用SpringMvc實現:
/*DOGET請求方式*/
@RequestMapping(value = "/dogetserver1" ,produces={"text/html;charset=UTF-8;","application/json;charset=UTF-8;"},method = RequestMethod.GET)
@ResponseBody
public String dogetserver1(@RequestParam(required=false, defaultValue="-1") String MulStr) {
Map<String, Object> map= new HashMap<String, Object>();
map.put("name", "李俏蕊");
map.put("age", "25");
JSONObject jsonObject=new JSONObject(map);
String response=jsonObject.toJSONString();
System.out.println("請求報文:"+MulStr);
System.out.println("返回報文:"+response);
return response;
}
@RequestMapping(value = "/dogetserver2",produces={"text/html;charset=UTF-8;","application/json;charset=UTF-8;"}, method = RequestMethod.GET)
@ResponseBody
public String dogetserver2() {
Map<String, Object> map= new HashMap<String, Object>();
map.put("name", "李俏蕊");
map.put("age", "25");
JSONObject jsonObject=new JSONObject(map);
String response=jsonObject.toJSONString();
System.out.println("返回報文:"+response);
return response;
}
@RequestMapping(value = "/dogetserver3",produces={"text/html;charset=UTF-8;","application/json;charset=UTF-8;"}, method = RequestMethod.GET)
@ResponseBody
public String dogetserver3(int id) {
System.out.println("id:"+id);
Map<String, Object> map= new HashMap<String, Object>();
map.put("name", "李俏蕊");
map.put("age", "25");
JSONObject jsonObject=new JSONObject(map);
String response=jsonObject.toJSONString();
System.out.println("返回報文:"+response);
return response;
}
@RequestMapping(value = "/dogetserver4",produces={"text/html;charset=UTF-8;","application/json;charset=UTF-8;"}, method = RequestMethod.GET)
@ResponseBody
public String dogetserver4(HttpServletRequest request) {
System.out.println("請求報文name:"+request.getParameter("name"));
System.out.println("請求報文age:"+request.getParameter("age"));
Map<String, Object> map= new HashMap<String, Object>();
map.put("name", "李俏蕊");
map.put("age", "25");
JSONObject jsonObject=new JSONObject(map);
String response=jsonObject.toJSONString();
System.out.println("返回報文:"+response);
return response;
}
2 .DOPOST方式調用
package com.client.Utils;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.UnsupportedEncodingException;
import java.nio.charset.Charset;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import org.apache.commons.httpclient.HttpClient;
import org.apache.commons.httpclient.HttpStatus;
import org.apache.commons.httpclient.NameValuePair;
import org.apache.commons.httpclient.methods.PostMethod;
import org.apache.commons.httpclient.methods.StringRequestEntity;
import org.apache.commons.httpclient.methods.multipart.MultipartRequestEntity;
import org.apache.commons.httpclient.methods.multipart.Part;
import org.apache.commons.httpclient.params.HttpConnectionManagerParams;
import org.apache.commons.io.IOUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.util.StreamUtils;
public class ClientUtilsByPost{
private static final Logger logger = LoggerFactory.getLogger(ClientUtilsByPost.class);
/** (常用)
* 執行一個HTTP POST請求,返回請求響應的HTML
*
* @param url 請求的URL地址
* @param reqStr 請求的查詢參數,可以爲null
* @param contentType 數據類型
* @param charset 字符集
* @return 返回請求響應的HTML
*/
public static String doPost(String url, String reqStr, String contentType, String charset) {
System.out.println("發送報文:"+reqStr);
String resultStr="";
HttpClient client = new HttpClient();
PostMethod method = new PostMethod(url);
try {
HttpConnectionManagerParams managerParams = client.getHttpConnectionManager().getParams();
managerParams.setConnectionTimeout(30000); // 設置連接超時時間(單位毫秒)
managerParams.setSoTimeout(30000); // 設置讀數據超時時間(單位毫秒)
method.setRequestEntity(new StringRequestEntity(reqStr, contentType, charset));
System.out.println("發送報文4:"+reqStr);
client.executeMethod(method);
System.out.println("返回的狀態碼爲:" +method.getStatusCode());
if (method.getStatusCode() == HttpStatus.SC_OK) {
resultStr= IOUtils.toString(method.getResponseBodyAsStream(),"UTF-8");
return resultStr;
}
} catch (UnsupportedEncodingException e1) {
logger.error(e1.getMessage());
return resultStr;
} catch (IOException e) {
logger.error("執行HTTP Post請求" + url + "時,發生異常!" + e.toString());
return resultStr;
} finally {
method.releaseConnection();
}
return resultStr;
}
/**
*
* @param url 請求的URL地址
* @param map 請求的map參數
* @return 返回請求響應的JSON字符串
* @throws UnsupportedEncodingException
*/
public static String doPost(String url, Map<String, Object> map) {
String response="";
HttpClient httpClient=new HttpClient();
PostMethod postMethod=new PostMethod(url);
List<NameValuePair> nameValuePairs=new ArrayList<NameValuePair>();
if(map!=null) {
for(Map.Entry<String, Object> entry : map.entrySet()) {
nameValuePairs.add(new NameValuePair(entry.getKey(),entry.getValue().toString()));
}
}
// 填入各個表單域的值
NameValuePair[] param = nameValuePairs.toArray(new NameValuePair[nameValuePairs.size()]);
System.out.println(param[0].getName()+"="+param[0].getValue());
postMethod.setRequestHeader("Content-Type", "application/x-www-form-urlencoded;charset=utf-8;");
// 將表單的值放入postMethod中
postMethod.addParameters(param);
try {
// 執行postMethod
httpClient.executeMethod(postMethod);
if (postMethod.getStatusCode() == HttpStatus.SC_OK) {
response= StreamUtils.copyToString(postMethod.getResponseBodyAsStream(), Charset.forName("utf-8"));
}
} catch (UnsupportedEncodingException e1) {
logger.error(e1.getMessage());
return response;
} catch (IOException e) {
logger.error("執行HTTP Post請求" + url + "時,發生異常!" + e.toString());
return response;
} finally {
postMethod.releaseConnection();
}
return response;
}
/**
* 執行一個HTTP POST請求,返回請求響應的HTML
*
* @param url 請求的URL地址
* @param reqStr 請求的查詢參數,可以爲null
* @param charset 字符集
* @return 返回請求響應的HTML
*/
public static String doPostMuStr(String url, Part[] reqStr) {
HttpClient client = new HttpClient();
PostMethod method = new PostMethod(url);
try {
HttpConnectionManagerParams managerParams = client.getHttpConnectionManager().getParams();
managerParams.setConnectionTimeout(30000); // 設置連接超時時間(單位毫秒)
managerParams.setSoTimeout(30000); // 設置讀數據超時時間(單位毫秒)
// method.getParams().setParameter(HttpMethodParams.HTTP_CONTENT_CHARSET, "utf-8");
method.setRequestEntity(new MultipartRequestEntity(reqStr, method.getParams()));
// method.setContentChunked(true);
client.executeMethod(method);
System.out.println("返回的狀態碼爲:" +method.getStatusCode());
if (method.getStatusCode() == HttpStatus.SC_OK) {
return IOUtils.toString(method.getResponseBodyAsStream(),"utf-8");
}
} catch (UnsupportedEncodingException e1) {
logger.error(e1.getMessage());
return "";
} catch (IOException e) {
logger.error("執行HTTP Post請求" + url + "時,發生異常!" + e.toString());
return "";
} finally {
method.releaseConnection();
}
return null;
}
}
調用主程序:
package com.client.test;
import java.io.UnsupportedEncodingException;
import java.util.HashMap;
import java.util.Map;
import org.apache.commons.httpclient.URI;
import org.apache.commons.httpclient.URIException;
import org.apache.commons.httpclient.methods.multipart.Part;
import org.apache.commons.httpclient.methods.multipart.StringPart;
import com.alibaba.fastjson.JSONObject;
import com.client.Utils.ClientUtilsByGet;
import com.client.Utils.ClientUtilsByPost;
/**
* Hello world!
*
*/
public class ClientTest
{
public static void main( String[] args ) throws URIException, NullPointerException
{
// String url="http://127.0.0.1:8080/SpringMvcService/dogetserver2?MulStr=111";
// URI u= new URI(url, true, "utf-8");
// System.out.println(urlbypost());
// System.out.println(urlbypost2());
// System.out.println(urlbypost3());
}
public static String urlbypost() {
String url="http://127.0.0.1:8080/SpringMvcService/student";
String reqStr=null;
String contentType="application/json";
String charset="UTF-8";
String resp=null;
Map<String, Object> map= new HashMap<String, Object>();
map.put("name", "李俏蕊");
map.put("age", "25");
JSONObject jsonObject=new JSONObject(map);
reqStr=jsonObject.toJSONString();
System.out.println("發送報文:"+reqStr);
resp=ClientUtilsByPost.doPost(url, reqStr, contentType, charset);
return resp;
}
public static String urlbypost2() {
String url="http://127.0.0.1:8080/SpringMvcService/doPost1";
// String reqStr=null;
// String contentType="application/x-www-form-urlencoded";
// String charset="UTF-8";
String resp=null;
Map<String, Object> map= new HashMap<String, Object>();
map.put("name", "李俏蕊");
map.put("age", "25");
resp=ClientUtilsByPost.doPost(url,map);
return resp;
}
public static String urlbypost3() {
String url="http://127.0.0.1:8080/SpringMvcService/fileupload";
// String reqStr=null;
// String contentType="application/x-www-form-urlencoded";
// String charset="UTF-8";
String resp=null;
Part[] parts=new Part[2];
parts[0]= new StringPart("name", "李俏蕊");
parts[1]= new StringPart("age", "25");
resp=ClientUtilsByPost.doPostMuStr(url,parts);
return resp;
}
}
Springmvc服務端:
@RequestMapping(value = "/student" ,produces={"text/html;charset=UTF-8;","application/json;charset=UTF-8;"})
@ResponseBody
public String student(@RequestBody String MulStr) {
Map<String, Object> map= new HashMap<String, Object>();
map.put("name", "李俏蕊");
map.put("age", "25");
JSONObject jsonObject=new JSONObject(map);
String response=jsonObject.toJSONString();
System.out.println("請求報文:"+MulStr);
System.out.println("返回報文:"+response);
return response;
}
@RequestMapping(value = "/doPost" ,produces={"text/html;charset=UTF-8;","application/json;charset=UTF-8;", "application/x-www-form-urlencoded;charset=UTF-8;"}, method = RequestMethod.POST)
@ResponseBody
public String doPost(@RequestBody String MulStr) throws UnsupportedEncodingException {
Map<String, Object> map= new HashMap<String, Object>();
map.put("name", "李俏蕊");
map.put("age", "25");
JSONObject jsonObject=new JSONObject(map);
String response=jsonObject.toJSONString();
System.out.println("請求報文:"+MulStr);
System.out.println("返回報文:"+response);
return response;
}
@RequestMapping(value = "/doPost1" ,produces={"text/html;charset=UTF-8;","application/json;charset=UTF-8;", "application/x-www-form-urlencoded;charset=UTF-8;"}, method = RequestMethod.POST)
@ResponseBody
public String doPost1(HttpServletRequest httpServletRequest ) throws UnsupportedEncodingException {
Map<String, Object> map= new HashMap<String, Object>();
map.put("name", "李俏蕊");
map.put("age", "25");
JSONObject jsonObject=new JSONObject(map);
String response=jsonObject.toJSONString();
System.out.println("請求報文:"+httpServletRequest.getParameter("name"));
System.out.println("請求報文:"+httpServletRequest.getParameter("age"));
System.out.println("返回報文:"+response);
return response;
}
@RequestMapping("/fileupload")
@ResponseBody
public String fileupload( HttpServletRequest request) throws UnsupportedEncodingException{
String aa="";
File path = new File("voicefilePath");
if(!path.exists())
path.mkdirs();
MultipartRequest multirequest = null;
try {
multirequest = new MultipartRequest(request,path.getAbsolutePath(),"UTF-8");
} catch (IOException e) {
e.printStackTrace();
}
System.out.println(multirequest.getParameter("name"));
String response = new String(multirequest.getParameter("age").getBytes("UTF-8"),"ISO-8859-1");
System.out.println(response);
return response;
}
運行結果:
最後總結 springmvc 在處理 請求時 post 使用@RequestBody 接收請求信息
表單 文件可以使用HttpServletRequest接收
GET請求 @RequestParam 接收處理 或者不使用標籤
public String dogetserver1(@RequestParam(required=false, defaultValue="-1") String MulStr)
required flase 表示 MulStr非必輸字段;
defaultValue -1 表示 MulStr 如果不傳值默認是-1處理
可以直接瀏覽器訪問
http://127.0.0.1:8080/SpringMvcService/dogetserver1?MulStr=tttt
http://127.0.0.1:8080/SpringMvcService/dogetserver1
都可以訪問
項目代碼已打包上傳,可以直接下載。
//download.csdn.net/download/xiaolenglala/11973567