上兩章我們分別利用Spring rmi和httpinvoker實現的遠程訪問功能,具體見《Spring 實現遠程訪問詳解——httpinvoker》和《Spring 實現遠程訪問詳解——rmi》和《Spring 實現遠程訪問詳解——webservice》
本章將通過apache httpclient實現遠程訪問。說得簡單就是直接通過spring requestmapping即請求映射url訪問遠程服務。1. 遠程訪問流程
1) 服務器在控制器定義遠程訪問請求映射路徑
2) 客戶端通過apache httpclient的 httppost方式訪問遠程服務
2. Httpclient方式具體實現
1) maven引入依賴
<dependency>
<groupId>org.apache.httpcomponents</groupId>
<artifactId>httpclient</artifactId>
<version>4.5.2</version>
</dependency></span>
2) 服務器在控制器定義遠程訪問請求映射路徑
@RequestMapping(value="/httpClientTest")
@ResponseBody
public BaseMapVo httpClientTest(String name, String password){
BaseMapVo vo = new BaseMapVo();
List<User> users = userService.getUserByAcount(name, password);
vo.addData("user", users);
vo.setRslt("success");
return vo;
3) 客戶端定義httpClient
package com.lm.core.util;
import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.io.InputStream;
importjava.io.UnsupportedEncodingException;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import org.apache.http.HttpResponse;
import org.apache.http.NameValuePair;
importorg.apache.http.client.ClientProtocolException;
importorg.apache.http.client.entity.UrlEncodedFormEntity;
importorg.apache.http.client.methods.CloseableHttpResponse;
importorg.apache.http.client.methods.HttpPost;
import org.apache.http.impl.client.CloseableHttpClient;
importorg.apache.http.impl.client.HttpClients;
importorg.apache.http.message.BasicNameValuePair;
public class HttpClientUtil implementsRunnable {
/**
* 不能在主線程中訪問網絡所以這裏另新建了一個實現了Runnable接口的Http訪問類
*/
private String name;
private String password;
private String path;
public HttpClientUtil(String name, String password,String path) {
// 初始化用戶名和密碼
this.name = name;
this.password = password;
this.path = path;
}
@Override
public void run() {
// 設置訪問的Web站點
// 設置Http請求參數
Map<String, String> params = new HashMap<String, String>();
params.put("name", name);
params.put("password", password);
String result = sendHttpClientPost(path, params, "utf-8");
// 把返回的接口輸出
System.out.println(result);
}
/**
* 發送Http請求到Web站點
*
* @param path
* Web站點請求地址
* @param map
* Http請求參數
* @param encode
* 編碼格式
* @return Web站點響應的字符串
*/
private String sendHttpClientPost(String path, Map<String, String>map,
String encode) {
List<NameValuePair> list = new ArrayList<NameValuePair>();
if (map != null && !map.isEmpty()) {
for (Map.Entry<String, String> entry : map.entrySet()) {
// 解析Map傳遞的參數,使用一個鍵值對對象BasicNameValuePair保存。
list.add(newBasicNameValuePair(entry.getKey(), entry
.getValue()));
}
}
HttpPost httpPost = null;
CloseableHttpClient client = null;
InputStream inputStream = null;
try {
// 實現將請求的參數封裝封裝到HttpEntity中。
UrlEncodedFormEntity entity = new UrlEncodedFormEntity(list, encode);
// 使用HttpPost請求方式
httpPost = new HttpPost(path);
// 設置請求參數到Form中。
httpPost.setEntity(entity);
// 實例化一個默認的Http客戶端
client = HttpClients.createDefault();
// HttpClient client = newDefaultHttpClient();
// 執行請求,並獲得響應數據
CloseableHttpResponse httpResponse = client.execute(httpPost);
// 判斷是否請求成功,爲200時表示成功,其他均問有問題。
System.err.println("status:"+httpResponse.getStatusLine().getStatusCode());
try{
if(httpResponse.getStatusLine().getStatusCode() == 200) {
// 通過HttpEntity獲得響應流
inputStream =httpResponse.getEntity().getContent();
returnchangeInputStream(inputStream, encode);
}
}finally{
if( null != httpResponse){
httpResponse.close();
}
if(null != inputStream){
inputStream.close();
}
}
} catch (UnsupportedEncodingException e) {
e.printStackTrace();
} catch (ClientProtocolException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}finally{
if(null != client){
try {
client.close();
}catch (IOException e) {
//TODO Auto-generated catch block
e.printStackTrace();
}
}
}
return "";
}
/**
* 把Web站點返回的響應流轉換爲字符串格式
*
* @param inputStream
* 響應流
* @param encode
* 編碼格式
* @return 轉換後的字符串
*/
private String changeInputStream(InputStream inputStream, String encode){
ByteArrayOutputStream outputStream = new ByteArrayOutputStream();
byte[] data = new byte[1024];
int len = 0;
String result = "";
if (inputStream != null) {
try {
while ((len =inputStream.read(data)) != -1) {
outputStream.write(data, 0,len);
}
result = newString(outputStream.toByteArray(), encode);
} catch (IOException e) {
e.printStackTrace();
}finally{
if(outputStream != null){
try {
outputStream.close();
}catch (IOException e) {
//TODO Auto-generated catch block
e.printStackTrace();
}
}
}
}
return result;
}
}
4) 客戶端訪問遠程服務
@RequestMapping(value = "/httpClientTest")
@ResponseBody
public BaseMapVo httpClientTest(String name, String password) {
BaseMapVo vo = new BaseMapVo();
long startDate = Calendar.getInstance().getTimeInMillis();
System.out.println("httpInvoker客戶端開始調用" + startDate);
String path="http://127.0.0.1:8080/spring_remote_server/user/httpClientTest";
HttpClientUtil httpClientUtil = new HttpClientUtil(name, password, path);
new Thread(httpClientUtil).start();
// UserHttpService rmi = (UserHttpService)ApplicationContextUtil.getInstance().getBean("httpInvokerProxy");
// rmi.getUserByAcount("張三", ":張三的密碼");
System.out.println("httpInvoker客戶端調用結束" + (Calendar.getInstance().getTimeInMillis()-startDate));
vo.setRslt("sucess");
return vo;
}
代碼下載:http://download.csdn.net/detail/a123demi/9495928