/**
*
* 依賴的夾包:coommons-httpclient-3.1.jar commons-codec-1.7.jar
* @param url
* @param 參數是: url, json:json格式的字符串
* @return
*/
public static String doPost(String url,String json){
String response="";
//創建HttpClient對象
HttpClient httpClient = new HttpClient();
httpClient.getHttpConnectionManager().getParams().setConnectionTimeout(50000); // 連接5秒超時
httpClient.getHttpConnectionManager().getParams().setSoTimeout(70000);// 讀取30秒超時
//通過PostMethod來創建鏈接,生成一個post請求
PostMethod method=new PostMethod(url);
try {
RequestEntity r=new StringRequestEntity(json);
//RequestBody或是RequestEntity作用是提供傳參,
//method.setRequestBody(json);//只對整個body
method.setRequestEntity(r);//可以是分段的內容,RequestEntity是一個接口,有很多實現可以傳遞不同類型的的參數
//允許客戶端或服務器中任何一方關閉底層的連接雙方都會要求在處理請求后關閉它們的TCP連接
method.setRequestHeader("Connection", "close");
method.setRequestHeader("Content-type", "application/json; charset=UTF-8");
//通過httpClient實例里的方法來實例化method
httpClient.executeMethod(method);
//讀 response,返回的結果
response = method.getResponseBodyAsString();
} catch (HttpException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}finally{
//釋放鏈接
method.releaseConnection();
}
return response;
}
======================
注解:HttpClient使用的步驟一般是如下:
1. 創建 HttpClient 的實例
2. 創建某種連接方法的實例method 實例,例如 GetMethod、PostMethod, 在 method 實例 的構造函數中傳入要連接的地址
3. 調用第一步中創建好的實例的 execute 方法來執行第二步中創建好的 method 實例
4. 讀 response,獲取返回數據
5. 釋放連接。無論執行方法是否成功,都必須釋放連接
6. 對得到后的內容進行處理
另外:PostMethod提供了方法來傳遞參數:setRequestBody和setRequestEntity(r)
RequestEntity的好處是有許多實現類來處理不同的資源
例如:你的參數是個流可以用InputStreamRequestEntity來構造RequestEntity
如果參數是字符串可以用StringRequestEntity來構造RequestEntity
如果是文件可以用FileRequestEntity來構造RequestEntity,還有其他的可以百度一下
====================實現方法如下====================
我是用的是Java,框架是spring+springMVC+mybitis
/**
* 測試http請求
* http://localhost:80/autopart/testhttp/testhttp1.do
*/
@RequestMapping("/testhttp")
@Controller
public class TestHttpController {
@RequestMapping(value="/testhttp1")
@ResponseBody
public String testHello(HttpServletRequest request ,HttpServletResponse response){
//String url="http://localhost:8080/blind/testhttp/testhttp1.do";
String url="http://localhost:80/autopart/testhttp/testhttp2.do";
String json= "{\"id\":1001,\"name\":\"藍星\"}";
String returns=HttpUtils.doPost(url, json);
System.err.println(returns);
return returns;
}
@ResponseBody
@RequestMapping(value = "/testhttp2", method = {
RequestMethod.GET, RequestMethod.POST }, produces = "application/json;charset=utf-8")
public String testHello(@RequestBody Map map){
String name=(String)map.get("name");
System.out.println("id是:"+10+",name是:"+name);
return "id是:"+10+",name是:"+name;
}
}
注解:
我測試的方法是:寫了一個測試類,通過第一個方法調用本類里的第二個方法通過http,調通就可以了
另外:上面第一個方法中注釋的url,是我調用的別的項目里的方法,也調通了
大概做法是:在我的電腦上(Windows),D盤和F盤分別裝了兩個tomcat,啟動兩個eclipce,一個引用了D盤的tomcate,一個引用了F盤的tomcate
在兩個eclipce中分別運行blind項目和autopart項目,從autopart項目中調用blind的方法,參數傳到了blind項目的方法中,並得到了返回的信息打印在了autopart控制台上
這就簡單實現了:同一個系統上不同服務器上的不同項目之間的信息傳遞,使用httpClient
