客户端向服务器发起http远程调用的几种方法

一、使用HttpClient发起远程http接口调用

     1、引入maven依赖如下:

1 <dependency>
2     <groupId>commons-httpclient</groupId>
3     <artifactId>commons-httpclient</artifactId>
4     <version>3.1</version>
5 </dependency>

    2、发送GET、POST、PUT、DELETE请求(application/jso格式)

    

  1 package com.java.example.utils;
  2 
  3 import lombok.extern.slf4j.Slf4j;
  4 import org.apache.commons.httpclient.HttpClient;
  5 import org.apache.commons.httpclient.NameValuePair;
  6 import org.apache.commons.httpclient.methods.PostMethod;
  7 import org.apache.commons.httpclient.methods.PutMethod;
  8 import org.apache.http.HttpEntity;
  9 import org.apache.http.client.ClientProtocolException;
 10 import org.apache.http.client.config.RequestConfig;
 11 import org.apache.http.client.methods.CloseableHttpResponse;
 12 import org.apache.http.client.methods.HttpDelete;
 13 import org.apache.http.client.methods.HttpPost;
 14 import org.apache.http.client.methods.HttpPut;
 15 import org.apache.http.entity.StringEntity;
 16 import org.apache.http.impl.client.CloseableHttpClient;
 17 import org.apache.http.impl.client.HttpClients;
 18 import org.apache.http.util.EntityUtils;
 19 
 20 import java.io.BufferedReader;
 21 import java.io.IOException;
 22 import java.io.InputStreamReader;
 23 import java.util.List;
 24 import java.util.Map;
 25 
 26 
 27 @Slf4j
 28 public class HttpClientUtil {
 29 
 30     /**
 31      * 发送GET请求,application/x-www-form-urlencoded格式
 32      */
 33     public static String sendGet(String url, Map<String, String> parameters) {
 34         String result = "";
 35         BufferedReader in = null;// 读取响应输入流
 36         StringBuffer sb = new StringBuffer();// 存储参数
 37         String params = "";// 编码之后的参数
 38         try {
 39             // 编码请求参数
 40             if (parameters.size() == 1) {
 41                 for (String name : parameters.keySet()) {
 42                     sb.append(name).append("=").append(
 43                             java.net.URLEncoder.encode(parameters.get(name),
 44                                     "UTF-8"));
 45                 }
 46                 params = sb.toString();
 47             } else {
 48                 for (String name : parameters.keySet()) {
 49                     sb.append(name).append("=").append(
 50                             java.net.URLEncoder.encode(parameters.get(name),
 51                                     "UTF-8")).append("&");
 52                 }
 53                 String temp_params = sb.toString();
 54                 params = temp_params.substring(0, temp_params.length() - 1);
 55             }
 56             String full_url = url + "?" + params;
 57             // 创建URL对象
 58             java.net.URL connURL = new java.net.URL(full_url);
 59             // 打开URL连接
 60             java.net.HttpURLConnection httpConn = (java.net.HttpURLConnection) connURL
 61                     .openConnection();
 62             // 设置通用属性
 63             httpConn.setRequestProperty("Content-type", "application/x-www-form-urlencoded");
 64             httpConn.setRequestProperty("Accept", "*/*");
 65             httpConn.setRequestProperty("Connection", "Keep-Alive");
 66             httpConn.setRequestProperty("User-Agent", "Mozilla/4.0 (compatible; MSIE 8.0; Windows NT 6.1)");
 67             // 建立实际的连接
 68             httpConn.connect();
 69             // 响应头部获取
 70             Map<String, List<String>> headers = httpConn.getHeaderFields();
 71             // 遍历所有的响应头字段
 72             for (String key : headers.keySet()) {
 73                 System.out.println(key + "\t:\t" + headers.get(key));
 74             }
 75             // 定义BufferedReader输入流来读取URL的响应,并设置编码方式
 76             in = new BufferedReader(new InputStreamReader(httpConn
 77                     .getInputStream(), "UTF-8"));
 78             String line;
 79             // 读取返回的内容
 80             while ((line = in.readLine()) != null) {
 81                 result += line;
 82             }
 83         } catch (Exception e) {
 84             log.info("HttpClientUtil sendGet exception.message=[{}]", e.getMessage());
 85             throw new RuntimeException("message=[{}],cause=[{}]"+e.getMessage(),e.getCause());
 86         }
 87         return result;
 88     }
 89 
 90     /**
 91      * 发送POST请求,application/x-www-form-urlencoded
 92      */
 93     public static String sendPost(String url, Map<String, String> requestHeaders, Map<String, String> requestBody) {
 94         try {
 95             PostMethod postMethod = new PostMethod(url);
 96             postMethod.setRequestHeader("Content-Type", "application/x-www-form-urlencoded;charset=utf-8");
 97             for (Map.Entry<String, String> entry : requestHeaders.entrySet()) {
 98                 postMethod.setRequestHeader(entry.getKey(), entry.getValue());
 99             }
100             //参数设不能传NULL,可以传传空字符串
101             NameValuePair[] data = new NameValuePair[requestBody.size()];
102             int i = 0;
103             for (Map.Entry<String, String> entry : requestBody.entrySet()) {
104                 data[i] = new NameValuePair(entry.getKey(), entry.getValue());
105                 i++;
106             }
107             postMethod.setRequestBody(data);
108 
109             org.apache.commons.httpclient.HttpClient httpClient = new org.apache.commons.httpclient.HttpClient();
110             int response = httpClient.executeMethod(postMethod); // 执行POST方法
111             String result = postMethod.getResponseBodyAsString();
112 
113             return result;
114         } catch (Exception e) {
115             throw new RuntimeException("message=[{}],cause=[{}]"+e.getMessage(),e.getCause());
116         }
117     }
118 
119     /**
120      * 发送PUT请求,application/x-www-form-urlencoded
121      */
122     public static String sendPut(String url, Map<String, String> requestHeaders, Map<String, String> requestBody) {
123         try {
124             PutMethod putMethod = new PutMethod(url);
125             putMethod.setRequestHeader("Content-Type", "application/x-www-form-urlencoded;charset=utf-8");
126             for (Map.Entry<String, String> entry : requestHeaders.entrySet()) {
127                 putMethod.setRequestHeader(entry.getKey(), entry.getValue());
128             }
129             //参数设不能传NULL,可以传传空字符串
130             NameValuePair[] data = new NameValuePair[requestBody.size()];
131             int i = 0;
132             for (Map.Entry<String, String> entry : requestBody.entrySet()) {
133                 data[i] = new NameValuePair(entry.getKey(), entry.getValue());
134                 i++;
135             }
136             putMethod.setQueryString(data);
137             org.apache.commons.httpclient.HttpClient httpClient = new org.apache.commons.httpclient.HttpClient();
138             int response = httpClient.executeMethod(putMethod); // 执行PUT方法
139             String result = putMethod.getResponseBodyAsString();
140 
141             return result;
142         } catch (Exception e) {
143             log.info("HttpClientUtil sendGet exception.message=[{}]", e.getMessage());
144             throw new RuntimeException("message=[{}],cause=[{}]"+e.getMessage(),e.getCause());
145         }
146     }
147 
148     /**
149      * 原生字符串发送put请求,application/x-www-form-urlencoded
150      */
151     public static String doPut(String url, String jsonStr, Map<String, String> requestHeaders) {
152 
153         CloseableHttpClient httpClient = HttpClients.createDefault();
154         HttpPut httpPut = new HttpPut(url);
155         RequestConfig requestConfig = RequestConfig.custom().setConnectTimeout(35000).setConnectionRequestTimeout(35000).setSocketTimeout(60000).build();
156         httpPut.setConfig(requestConfig);
157         httpPut.setHeader("Content-type", "application/x-www-form-urlencoded;charset=utf-8");
158         httpPut.setHeader("DataEncoding", "UTF-8");
159         if (!requestHeaders.isEmpty()) {
160             for (Map.Entry entry : requestHeaders.entrySet()) {
161                 httpPut.setHeader(String.valueOf(entry.getKey()), String.valueOf(entry.getValue()));
162             }
163         }
164         CloseableHttpResponse httpResponse = null;
165         try {
166             httpPut.setEntity(new StringEntity(jsonStr));
167             httpResponse = httpClient.execute(httpPut);
168             HttpEntity entity = httpResponse.getEntity();
169             String result = EntityUtils.toString(entity);
170             return result;
171         } catch (ClientProtocolException e) {
172             log.info("HttpClientUtil doPut exception.message=[{}]", e.getMessage());
173             throw new RuntimeException("message=[{}],cause=[{}]"+e.getMessage(),e.getCause());
174         } catch (IOException e) {
175             log.info("HttpClientUtil doPut exception.message={}" + e.getMessage());
176             throw new RuntimeException("message=[{}],cause=[{}]"+e.getMessage(),e.getCause());
177         }
178     }
179 
180     /**
181      * 发送delete请求,application/x-www-form-urlencoded
182      */
183     public static String doDelete(String url, Map<String, String> requestHeaders) {
184 
185         CloseableHttpClient httpClient = HttpClients.createDefault();
186         HttpDelete httpDelete = new HttpDelete(url);
187         RequestConfig requestConfig = RequestConfig.custom().setConnectTimeout(35000).setConnectionRequestTimeout(35000).setSocketTimeout(60000).build();
188         httpDelete.setConfig(requestConfig);
189         httpDelete.setHeader("Content-type", "application/x-www-form-urlencoded");
190         httpDelete.setHeader("DataEncoding", "UTF-8");
191         if (!requestHeaders.isEmpty()) {
192             for (Map.Entry entry : requestHeaders.entrySet()) {
193                 httpDelete.setHeader(String.valueOf(entry.getKey()), String.valueOf(entry.getValue()));
194             }
195         }
196 
197         CloseableHttpResponse httpResponse = null;
198         try {
199             httpResponse = httpClient.execute(httpDelete);
200             HttpEntity entity = httpResponse.getEntity();
201             String result = EntityUtils.toString(entity);
202             return result;
203         } catch (ClientProtocolException e) {
204             throw new RuntimeException("message=[{}],cause=[{}]"+e.getMessage(),e.getCause());
205         } catch (IOException e) {
206             throw new RuntimeException("message=[{}],cause=[{}]"+e.getMessage(),e.getCause());
207         }
208     }
209 
210     /**
211      * 原生字符串发送post请求,application/x-www-form-urlencoded
212      */
213     public static String doPost(String url, String requestParams, Map<String, String> requestHeaders) {
214 
215         CloseableHttpClient httpClient = HttpClients.createDefault();
216         HttpPost httpPost = new HttpPost(url);
217         RequestConfig requestConfig = RequestConfig.custom().setConnectTimeout(35000).setConnectionRequestTimeout(35000).setSocketTimeout(60000).build();
218         httpPost.setConfig(requestConfig);
219         httpPost.setHeader("Content-type", "application/x-www-form-urlencoded");
220         httpPost.setHeader("DataEncoding", "UTF-8");
221         if (!requestHeaders.isEmpty()) {
222             for (Map.Entry entry : requestHeaders.entrySet()) {
223                 httpPost.setHeader(String.valueOf(entry.getKey()), String.valueOf(entry.getValue()));
224             }
225         }
226         CloseableHttpResponse httpResponse = null;
227         try {
228             String requestBody = EntityUtils.toString(new StringEntity(requestParams));
229             log.info("entity = [{}]", requestBody);
230             httpPost.setEntity(new StringEntity(requestParams));
231 
232             httpResponse = httpClient.execute(httpPost);
233             HttpEntity entity = httpResponse.getEntity();
234             String result = EntityUtils.toString(entity);
235             return result;
236         } catch (ClientProtocolException e) {
237             throw new RuntimeException("message=[{}],cause=[{}]"+e.getMessage(),e.getCause());
238         } catch (IOException e) {
239             throw new RuntimeException("message=[{}],cause=[{}]"+e.getMessage(),e.getCause());
240         }
241     }
242 
243     /**
244      * json格式专用POST请求,application/json;charset=utf-8格式
245      */
246     public static String doPostForJson(String url, String requestParams, Map<String, String> requestHeaders) {
247 
248         CloseableHttpClient httpClient = HttpClients.createDefault();
249         HttpPost httpPost = new HttpPost(url);
250         RequestConfig requestConfig = RequestConfig.custom().setConnectTimeout(35000).setConnectionRequestTimeout(35000).setSocketTimeout(60000).build();
251         httpPost.setConfig(requestConfig);
252         httpPost.setHeader("Content-type", "application/json;charset=utf-8");
253         httpPost.setHeader("DataEncoding", "UTF-8");
254         if (!requestHeaders.isEmpty()) {
255             for (Map.Entry entry : requestHeaders.entrySet()) {
256                 httpPost.setHeader(String.valueOf(entry.getKey()), String.valueOf(entry.getValue()));
257             }
258         }
259         CloseableHttpResponse httpResponse = null;
260         try {
261             String requestBody = EntityUtils.toString(new StringEntity(requestParams));
262             log.info("entity = [{}]", requestBody);
263             httpPost.setEntity(new StringEntity(requestParams));
264 
265             httpResponse = httpClient.execute(httpPost);
266             HttpEntity entity = httpResponse.getEntity();
267             String result = EntityUtils.toString(entity);
268             return result;
269         } catch (ClientProtocolException e) {
270             throw new RuntimeException("message=[{}],cause=[{}]"+e.getMessage(),e.getCause());
271         } catch (IOException e) {
272             throw new RuntimeException("message=[{}],cause=[{}]"+e.getMessage(),e.getCause());
273         }
274     }
275 
276     public static String doPostJson(String url, String key, String json) {
277         try {
278             String postURL = url;
279             PostMethod postMethod = null;
280             postMethod = new PostMethod(postURL);
281             postMethod.setRequestHeader("Content-Type", "application/x-www-form-urlencoded;charset=utf-8");
282             postMethod.addParameter(key, json);  //传参数
283             HttpClient httpClient = new HttpClient();
284             int response = httpClient.executeMethod(postMethod); // 执行POST方法
285             String result = postMethod.getResponseBodyAsString();
286             return result;
287         } catch (Exception e) {
288             throw new RuntimeException("message=[{}],cause=[{}]"+e.getMessage(),e.getCause());
289         }
290     }
291 }

 二、使用RestTemplate发起远程http接口调用

    1、引入maven依赖

    

        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-web</artifactId>
        </dependency>

    2、添加BeanConfig类

    

 1 package com.java.example.config;
 2 
 3 import org.springframework.context.annotation.Bean;
 4 import org.springframework.context.annotation.Configuration;
 5 import org.springframework.web.client.RestTemplate;
 6 
 7 @Configuration
 8 public class BeanConfig {
 9     @Bean
10     public RestTemplate restTemplate(){
11         return new RestTemplate();
12     }
13 }

    3、客户端发起远程http接口调用

    

 1 import com.java.example.utils;
 2 
 3 import java.util.Map;
 4 
 5 import org.springframework.http.HttpHeaders;
 6 import org.springframework.http.HttpEntity;
 7 import org.springframework.http.MediaType;
 8 
 9 /**
10  * @author Tomcat
11  * @data 2019-09-15 23:31
12  */
13 public class Test {
14 
15 
16     @Autowired
17     private RestTemplate restTemplate;
18 
19     @Autowired
20     private LoadBalancerClient loadBalancerClient;
21 
22     /**
23      * @author Tomcat
24      * @data 2019-11-17
25      */
26     public String doPost(Map<String, Object> requestHearder, UserDTO requestBody, String url) {
27 
28         HttpHeaders httpHeaders = new HttpHeaders();
29         httpHeaders.setContentType(MediaType.parseMediaType("application/json;charset=UTF-8"));
30         HttpEntity<UserDTO> requestEntity = new HttpEntity<UserDTO>(req, httpHeaders);
31         String response = restTemplate.postForObject(url, requestEntity, String.class);
32         return response;
33     }
34 
35     /**
36      * 利用loadBalancerClient通过应用名获取url,然后再使用restTemplate
37      *
38      * @param macroserviceName
39      * @return
40      */
41     public String doGet(String macroserviceName) {   // 用于微服务,根据服务名调用
42         ServiceInstance serviceInstance = loadBalancerClient.choose(macroserviceName);
43         String url = String.format("http://%s:s%", serviceInstance.getHost(), serviceInstance.getPort()) + "msg";
44         String response = restTemplate.getForObject(url, String.class);
45         return response;
46     }
47 
48     /**
49      * @param dto
50      * @return
51      */
52     public Result cancelOrder(OrderDto dto) {
53         Result result = Result.success();
54         String merSn = dto.getMerSn();
55         OrderCancelRequest request = new OrderCancelRequest();
56         BeanUtils.copyProperties(dto, request);
57         String jsonObj = JSON.toJSONString(request);
58         HttpHeaders headers = new HttpHeaders();
59         headers.setContentType(MediaType.APPLICATION_JSON_UTF8);
60         HttpEntity<String> httpEntity = new HttpEntity(jsonObj, headers);
61         String requestUrl = Order_Cancel_Url + "/order/{merSn}/cancel";
62         try {
63             restTemplate.put(requestUrl, httpEntity, merSn);
64         } catch (Exception e) {
65             return Result.fail("订单取消失败,请联系客服人员");
66         }
67 
68         return result;
69     }
70 
71     public boolean doDetele(String id) {
72         try {
73             restTemplate.delete("http://HELLO-SERVICE/getbook4/{1}", id);
74         } catch (Exception e) {
75             return false;
76         }
77         return true;
78     }
79 }

三、使用HttpURLConnection发起远程http接口调用

    

package com.java.example.utils;

import lombok.extern.slf4j.Slf4j;

import java.io.BufferedReader;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.OutputStream;
import java.net.HttpURLConnection;
import java.net.URL;
import java.net.URLConnection;

/**
 * @author Tomcat
 * @date 
 * @description:
 */
@Slf4j
public class HttpUtils {
    /**
     * http的post请求
     *
     * @param urlPath 请求路径
     * @param params 请求参数json格式字符串
     * @return 返回的值json格式字符串
     */
    public static String httpPost(String urlPath,String params) {

        try {
            URL url = new URL(urlPath);
            URLConnection urlConnection = url.openConnection();
            System.setProperty("sun.net.client.defaultConnectTimeout", "30000");
            System.setProperty("sun.net.client.defaultReadTimeout", "30000");
            urlConnection.setRequestProperty("Content-Type", "text/plain;charset=UTF-8");
            HttpURLConnection httpUrlConnection = (HttpURLConnection) urlConnection;
            httpUrlConnection.setDoOutput(true);
            httpUrlConnection.setDoInput(true);
            httpUrlConnection.setUseCaches(false);
            httpUrlConnection.setRequestMethod("POST");
            httpUrlConnection.connect();
            OutputStream outStrm = httpUrlConnection.getOutputStream();
            // 建立输入流,向指向的URL传入参数
            outStrm.write(params.getBytes("utf-8"));
            outStrm.flush();
            outStrm.close();
            // 获得响应状态
            int resultCode = httpUrlConnection.getResponseCode();
            if (HttpURLConnection.HTTP_OK == resultCode) {
                System.out.println("HTTP_OK");
                InputStream in = urlConnection.getInputStream();
                BufferedReader bufferedReader = new BufferedReader(new InputStreamReader(in));
                StringBuffer temp = new StringBuffer();
                String line = bufferedReader.readLine();
                while (line != null) {
                    temp.append(line).append("\r\n");
                    line = bufferedReader.readLine();
                }
                bufferedReader.close();
                return new String(temp.toString().getBytes(), "utf-8");
            }

        } catch (Exception e) {
            log.error(e.getMessage());
            throw new RuntimeException(e);
        }
        return null;
    }
}

 

posted @ 2020-03-08 00:12  骑着蜗牛看海呀  阅读(2500)  评论(0编辑  收藏  举报