Spring 实现远程访问详解——httpclient

来源:互联网 发布:http传输数据 编辑:程序博客网 时间:2024/06/06 03:25

上两章我们分别利用Spring rmi和httpinvoker实现的远程访问功能,具体见《Spring 实现远程访问详解——httpinvoker》和《Spring 实现远程访问详解——rmi》。本章将通过apache httpclient实现远程访问。说得简单就是直接通过spring requestmapping即请求映射url访问远程服务。

1.      远程访问流程

1)      服务器在控制器定义远程访问请求映射路径

2)      客户端通过apache httpclient的 httppost方式访问远程服务

2.      Httpclient方式具体实现

1) maven引入依赖

<span style="font-family:Times New Roman;"><dependency><groupId>org.apache.httpcomponents</groupId><artifactId>httpclient</artifactId><version>4.5.2</version></dependency></span>

2)      服务器在控制器定义远程访问请求映射路径

 

<span style="font-family:Times New Roman;">@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;}</span>

3)      客户端定义httpClient

<span style="font-family:Times New Roman;">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;    } }</span>

4)      客户端访问远程服务

@RequestMapping(value = "/httpClientTest")

<span style="font-family:Times New Roman;">    @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;    }</span>

代码下载:http://download.csdn.net/detail/a123demi/9495928

0 0
原创粉丝点击