VB.net 2010 视频教程 VB.net 2010 视频教程 python基础视频教程
SQL Server 2008 视频教程 c#入门经典教程 Visual Basic从门到精通视频教程
当前位置:
首页 > 编程开发 > Java教程 >
  • HTTP的post和get请求--httputils和resttemplate

  通过代码来代替postman来访问接口

一、通过jdk1.8自带的工具类直接请求

不需要导入任何jar包

 

复制代码
  1 package servlet;
  2 
  3 import java.io.BufferedReader;
  4 import java.io.IOException;
  5 import java.io.InputStream;
  6 import java.io.InputStreamReader;
  7 import java.io.PrintWriter;
  8 import java.net.ConnectException;
  9 import java.net.SocketTimeoutException;
 10 import java.net.URL;
 11 import java.net.URLConnection;
 12 import java.net.URLEncoder;
 13 import java.security.cert.X509Certificate;
 14 
 15 import javax.net.ssl.HostnameVerifier;
 16 import javax.net.ssl.HttpsURLConnection;
 17 import javax.net.ssl.SSLContext;
 18 import javax.net.ssl.SSLSession;
 19 import javax.net.ssl.TrustManager;
 20 import javax.net.ssl.X509TrustManager;
 21 
 22 import org.slf4j.Logger;
 23 import org.slf4j.LoggerFactory;
 24 
 25 /**
 26  * 通用http发送方法
 27  * 
 28  * @author ruoyi
 29  */
 30 public class HttpUt
 31 {
 32     private static final Logger log = LoggerFactory.getLogger(HttpUt.class);
 33 
 34     /**
 35      * 向指定 URL 发送GET方法的请求
 36      *
 37      * @param url 发送请求的 URL
 38      * @param param 请求参数,请求参数应该是 name1=value1&name2=value2 的形式。
 39      * @return 所代表远程资源的响应结果
 40      */
 41     public static String sendGet(String url, String param)
 42     {
 43         StringBuilder result = new StringBuilder();
 44         BufferedReader in = null;
 45         try
 46         {
 47             String urlNameString = url + "?" + param;
 48             log.info("sendGet - {}", urlNameString);
 49             URL realUrl = new URL(urlNameString);
 50             URLConnection connection = realUrl.openConnection();
 51             connection.setRequestProperty("accept", "*/*");
 52             connection.setRequestProperty("connection", "Keep-Alive");
 53             connection.setRequestProperty("user-agent", "Mozilla/4.0 (compatible; MSIE 6.0; Windows NT 5.1;SV1)");
 54             connection.connect();
 55             in = new BufferedReader(new InputStreamReader(connection.getInputStream()));
 56             String line;
 57             while ((line = in.readLine()) != null)
 58             {
 59                 result.append(line);
 60             }
 61             log.info("recv - {}", result);
 62         }
 63         catch (ConnectException e)
 64         {
 65             log.error("调用HttpUtils.sendGet ConnectException, url=" + url + ",param=" + param, e);
 66         }
 67         catch (SocketTimeoutException e)
 68         {
 69             log.error("调用HttpUtils.sendGet SocketTimeoutException, url=" + url + ",param=" + param, e);
 70         }
 71         catch (IOException e)
 72         {
 73             log.error("调用HttpUtils.sendGet IOException, url=" + url + ",param=" + param, e);
 74         }
 75         catch (Exception e)
 76         {
 77             log.error("调用HttpsUtil.sendGet Exception, url=" + url + ",param=" + param, e);
 78         }
 79         finally
 80         {
 81             try
 82             {
 83                 if (in != null)
 84                 {
 85                     in.close();
 86                 }
 87             }
 88             catch (Exception ex)
 89             {
 90                 log.error("调用in.close Exception, url=" + url + ",param=" + param, ex);
 91             }
 92         }
 93         return result.toString();
 94     }
 95 
 96     /**
 97      * 向指定 URL 发送POST方法的请求
 98      *
 99      * @param url 发送请求的 URL
100      * @param param 请求参数,请求参数应该是 name1=value1&name2=value2 的形式。
101      * @return 所代表远程资源的响应结果
102      */
103     public static String sendPost(String url, String param)
104     {
105         PrintWriter out = null;
106         BufferedReader in = null;
107         StringBuilder result = new StringBuilder();
108         try
109         {
110             String urlNameString = url + "?" + URLEncoder.encode(param, "UTF-8");
111             log.info("sendPost - {}", urlNameString);
112             URL realUrl = new URL(urlNameString);
113             URLConnection conn = realUrl.openConnection();
114             conn.setRequestProperty("accept", "*/*");
115             conn.setRequestProperty("connection", "Keep-Alive");
116             conn.setRequestProperty("user-agent", "Mozilla/4.0 (compatible; MSIE 6.0; Windows NT 5.1;SV1)");
117             conn.setRequestProperty("Accept-Charset", "utf-8");
118             conn.setRequestProperty("contentType", "utf-8");
119             conn.setDoOutput(true);
120             conn.setDoInput(true);
121             out = new PrintWriter(conn.getOutputStream());
122             out.print(param);
123             out.flush();
124             in = new BufferedReader(new InputStreamReader(conn.getInputStream(), "utf-8"));
125             String line;
126             while ((line = in.readLine()) != null)
127             {
128                 result.append(line);
129             }
130             log.info("recv - {}", result);
131         }
132         catch (ConnectException e)
133         {
134             log.error("调用HttpUtils.sendPost ConnectException, url=" + url + ",param=" + param, e);
135         }
136         catch (SocketTimeoutException e)
137         {
138             log.error("调用HttpUtils.sendPost SocketTimeoutException, url=" + url + ",param=" + param, e);
139         }
140         catch (IOException e)
141         {
142             log.error("调用HttpUtils.sendPost IOException, url=" + url + ",param=" + param, e);
143         }
144         catch (Exception e)
145         {
146             log.error("调用HttpsUtil.sendPost Exception, url=" + url + ",param=" + param, e);
147         }
148         finally
149         {
150             try
151             {
152                 if (out != null)
153                 {
154                     out.close();
155                 }
156                 if (in != null)
157                 {
158                     in.close();
159                 }
160             }
161             catch (IOException ex)
162             {
163                 log.error("调用in.close Exception, url=" + url + ",param=" + param, ex);
164             }
165         }
166         return result.toString();
167     }
168 
169     public static String sendSSLPost(String url, String param)
170     {
171         StringBuilder result = new StringBuilder();
172         String urlNameString = url + "?" + param;
173         try
174         {
175             log.info("sendSSLPost - {}", urlNameString);
176             SSLContext sc = SSLContext.getInstance("SSL");
177             sc.init(null, new TrustManager[] { new TrustAnyTrustManager() }, new java.security.SecureRandom());
178             URL console = new URL(urlNameString);
179             HttpsURLConnection conn = (HttpsURLConnection) console.openConnection();
180             conn.setRequestProperty("accept", "*/*");
181             conn.setRequestProperty("connection", "Keep-Alive");
182             conn.setRequestProperty("user-agent", "Mozilla/4.0 (compatible; MSIE 6.0; Windows NT 5.1;SV1)");
183             conn.setRequestProperty("Accept-Charset", "utf-8");
184             conn.setRequestProperty("contentType", "utf-8");
185             conn.setDoOutput(true);
186             conn.setDoInput(true);
187 
188             conn.setSSLSocketFactory(sc.getSocketFactory());
189             conn.setHostnameVerifier(new TrustAnyHostnameVerifier());
190             conn.connect();
191             InputStream is = conn.getInputStream();
192             BufferedReader br = new BufferedReader(new InputStreamReader(is));
193             String ret = "";
194             while ((ret = br.readLine()) != null)
195             {
196                 if (ret != null && !ret.trim().equals(""))
197                 {
198                     result.append(new String(ret.getBytes("ISO-8859-1"), "utf-8"));
199                 }
200             }
201             log.info("recv - {}", result);
202             conn.disconnect();
203             br.close();
204         }
205         catch (ConnectException e)
206         {
207             log.error("调用HttpUtils.sendSSLPost ConnectException, url=" + url + ",param=" + param, e);
208         }
209         catch (SocketTimeoutException e)
210         {
211             log.error("调用HttpUtils.sendSSLPost SocketTimeoutException, url=" + url + ",param=" + param, e);
212         }
213         catch (IOException e)
214         {
215             log.error("调用HttpUtils.sendSSLPost IOException, url=" + url + ",param=" + param, e);
216         }
217         catch (Exception e)
218         {
219             log.error("调用HttpsUtil.sendSSLPost Exception, url=" + url + ",param=" + param, e);
220         }
221         return result.toString();
222     }
223 
224     private static class TrustAnyTrustManager implements X509TrustManager
225     {
226         @Override
227         public void checkClientTrusted(X509Certificate[] chain, String authType)
228         {
229         }
230 
231         @Override
232         public void checkServerTrusted(X509Certificate[] chain, String authType)
233         {
234         }
235 
236         @Override
237         public X509Certificate[] getAcceptedIssuers()
238         {
239             return new X509Certificate[] {};
240         }
241     }
242 
243     private static class TrustAnyHostnameVerifier implements HostnameVerifier
244     {
245         @Override
246         public boolean verify(String hostname, SSLSession session)
247         {
248             return true;
249         }
250     }
251 }
复制代码

 

二、第二种工具类、(需要导入jar包和配置请求头)

1.所需jar包

 

 2.请求头的配置

复制代码
      String result= HttpUtil.init(url).setMethod(HttpUtil.POST)
      .addHeader("accept", "*/*")
      .addHeader("connection", "Keep-Alive")
      .addHeader("user-agent", "Mozilla/4.0 (compatible; MSIE 6.0; Windows NT 5.1;SV1)")
      .addHeader("contentType", "application/json;charset=utf-8")
      .addHeader("Transfer-Encoding", "chunked")
      .send(para);
复制代码

3.工具类

复制代码
  1 package servlet;
  2 
  3 import java.net.HttpURLConnection;
  4 import java.net.ProtocolException;
  5 import java.net.URL;
  6 import java.net.URLConnection;
  7 import java.util.Map;
  8 import java.util.Map.Entry;
  9 import org.apache.commons.codec.binary.Base64;
 10 import org.apache.commons.io.IOUtils;
 11 //import org.apache.log4j.Logger;
 12 
 13 /**
 14  * http 工具类
 15  * 
 16  *
 17  */
 18 public class HttpUtil {
 19     public static final String POST="POST";
 20     public static final String GET="GET";
 21     
 22     private HttpURLConnection connection;
 23         
 24     private HttpUtil(String url){
 25         try {
 26             connection= (HttpURLConnection) new URL(url).openConnection();
 27             connection.setDoInput(true);
 28             connection.setDoOutput(true);
 29         } catch (Exception e) {
 30 //            Logger.getLogger("com.rockontrol.error").error(e);
 31             connection= null;
 32         }
 33     }
 34     public static HttpUtil init(String url){
 35         HttpUtil httpUtil=new HttpUtil(url);        
 36         if(httpUtil.connection==null)
 37             return null;
 38         return httpUtil.setMethod(POST);
 39     }
 40     
 41     public HttpUtil addHeader(String type,String value){
 42         connIsNull();
 43         connection.addRequestProperty(type, value);
 44         return this;
 45     }
 46     public HttpUtil addHeader(Map<String, String> headers){
 47         for(Entry<String, String> entry:headers.entrySet())
 48             addHeader(entry.getKey(), entry.getValue());
 49         return this;
 50     }
 51     public HttpUtil setTimeout(int m){
 52         connIsNull();
 53         connection.setConnectTimeout(m);
 54         connection.setReadTimeout(m);
 55         return this;
 56     }
 57     public HttpUtil setMethod(String method){
 58         connIsNull();
 59         try {
 60             connection.setRequestMethod(method);
 61         } catch (ProtocolException e) {
 62 //            Logger.getLogger("com.rockontrol.error").error(e);
 63             return null;
 64         }
 65         return this;
 66     }
 67     
 68     public String send(String msg,String encode){
 69         connIsNull();
 70         try {
 71             if(!"".equals(msg)){
 72                 System.out.println("00");
 73                 IOUtils.write(msg, connection.getOutputStream(),encode);
 74                 System.out.println("11");
 75             }
 76             if(connection.getResponseCode()==HttpURLConnection.HTTP_OK) {
 77                 System.out.println("11");
 78                 return IOUtils.toString(connection.getInputStream(),encode);
 79             }else{
 80                 throw new RuntimeException("接受数据失败!"+connection.getResponseCode()+" : "+connection.getResponseMessage());
 81             }
 82         } catch (Exception e) {
 83 //            Logger.getLogger("com.rockontrol.error").error(e);
 84             return null;
 85         }finally{
 86             close();
 87         }
 88     }
 89     public String getImage(){
 90         connIsNull();
 91         try {
 92             IOUtils.write("", connection.getOutputStream());
 93 
 94             if(connection.getResponseCode()==HttpURLConnection.HTTP_OK){
 95                 //return IOUtils.toString(connection.getInputStream(),encode);
 96                 byte[] buffer=IOUtils.toByteArray(connection.getInputStream());
 97                 return Base64.encodeBase64String(buffer);
 98             }else{
 99                 throw new RuntimeException("接受数据失败!"+connection.getResponseCode()+" : "+connection.getResponseMessage());
100             }
101         } catch (Exception e) {
102 
103             return null;
104         }finally{
105             close();
106         }
107     }
108     public String send(String msg){
109         return send(msg,"UTF-8");
110     }
111     
112     public URLConnection getConnection(){
113         connIsNull();
114         return connection;
115     }
116     
117     public void close(){
118         IOUtils.close(connection);
119     }
120     
121     private void connIsNull(){
122         if(connection==null){
123             throw new RuntimeException("无法建立连接!");
124         }
125     }
126 }
复制代码

三、使用resttemplate 

 

复制代码
 1         RestTemplate client = new RestTemplate();
 2         HttpHeaders headers = new HttpHeaders();
 3         HttpMethod method = HttpMethod.GET;
 4 
 5         // 以表单的方式提交
 6 //        headers.setContentType(MediaType.APPLICATION_FORM_URLENCODED);
 7         //将请求头部和参数合成一个请求
 8         HttpEntity<MultiValueMap<String, String>> requestEntity = new HttpEntity<>(headers);
 9         //执行HTTP请求,将返回的结构使用ResultVO类格式化
10         ResponseEntity<String> response = client.exchange(url, method, requestEntity,String.class);
11         System.out.println("---------------"+response.getBody());
复制代码

原文:https://www.cnblogs.com/nntld/p/15627727.html


相关教程