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

本文介绍如何使用 Apache HttpClient 库实现远程访问的功能。主要内容包括远程访问的基本流程、客户端和服务端的具体实现步骤,以及如何通过 HttpClient 发送 POST 请求并接收响应。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

上两章我们分别利用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.youkuaiyun.com/detail/a123demi/9495928

博文转自:http://blog.youkuaiyun.com/a123demi/article/details/51206079
















评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值