转载

java模拟简易Http的get和post请求

背景

笔者做java web后台开发,经常需要和前端同学交互,由于前后台工作效率不一,总会有时间差,以前总时傻傻等待或是轮询:“喂,前端写好了没,交互一下”。之前也有师弟告诉我,火狐浏览器有自带模拟Http请求的插件,但是,作为一名程序猿,还是想通过代码自己写个工具类。于是乎,就有了HttpHelper。

设计

get和post协议是web开发最常用的两种方式,两者传输数据的不用在于:get请求将数据拼接在url地址里,而post请求则将数据放在请求体里。于是在工具类里定义两个方法相应的去处理两种请求,再将两个方法相同的地方(请求头设定,数据解析)抽取出来,代码复用。笔者做的web项目前后台交互数据均用json格式,因此数据存储在Map中。

代码

 package util;  import java.io.*; import java.net.HttpURLConnection; import java.net.MalformedURLException; import java.net.URL; import java.util.Iterator; import java.util.Map; import java.util.Set;  /**  * Simulating Http Request  * Created by Michael Wong on 2016/2/24.  */ public class HttpHelper {      private static final String GET_METHOD = "GET";      private static final String POST_METHOD = "POST";      private HttpHelper() {      }      /**      * Get request      * @param url       * @param parameters       * @return responseBody      */     public static String get(String url, Map<String, Object> parameters) {          url = url + "?" + parseParameters(parameters);          HttpURLConnection connection = null;          try {             URL httpUrl = new URL(url);             connection = (HttpURLConnection) httpUrl.openConnection();             connection.setRequestMethod(GET_METHOD);              setRequestProperty(connection);              connection.connect();              return receiveResponse(connection);          } catch (MalformedURLException e) {             e.printStackTrace();         } catch (IOException e) {             e.printStackTrace();         } finally {             if (connection != null) {                 connection.disconnect();             }         }          return null;     }      /**      * Post request      * @param url       * @param parameters       * @return responseBody      */     public static String post(String url, Map<String, Object> parameters) {          HttpURLConnection connection = null;         BufferedWriter writer = null;          try {             URL httpUrl = new URL(url);             connection = (HttpURLConnection) httpUrl.openConnection();             connection.setRequestMethod(POST_METHOD);              setRequestProperty(connection);              writer = new BufferedWriter(                     new OutputStreamWriter(connection.getOutputStream()));             writer.write(parseParameters(parameters));             writer.flush();              return receiveResponse(connection);          } catch (MalformedURLException e) {             e.printStackTrace();         } catch (IOException e) {             e.printStackTrace();         } finally {             try {                 if (writer != null) {                     writer.close();                 }             } catch (IOException e) {                 e.printStackTrace();             }             if (connection != null) {                 connection.disconnect();             }         }          return null;     }      /**      * Set Request Properties      * @param connection HttpConnection      */     private static void setRequestProperty(HttpURLConnection connection) {         connection.setRequestProperty("Accept", "application/json, text/javascript, */*; q=0.01");         connection.setRequestProperty("Content-Type", "application/x-www-form-urlencoded; charset=UTF-8");         connection.setRequestProperty("Accept-Language", "zh-CN,zh;q=0.8,en;q=0.6");         connection.setRequestProperty("Connection", "keep-alive");         connection.setRequestProperty("User-Agent", "Mozilla/5.0 " +                 "(Windows NT 6.1; WOW64) AppleWebKit/537.36 " +                 "(KHTML, like Gecko) Chrome/47.0.2526.111 Safari/537.36");         if (POST_METHOD.equals(connection.getRequestMethod())) {             connection.setDoOutput(true);         }         connection.setDoInput(true);     }      /**      * Parse parameters      * @param parameters       * @return parsed parameters      */     private static String parseParameters(Map<String, Object> parameters) {         if (parameters == null) {             return "";         }         StringBuilder result = new StringBuilder();         Set<Map.Entry<String, Object>> set = parameters.entrySet();         Iterator<Map.Entry<String, Object>> iterator = set.iterator();          while (iterator.hasNext()) {             Map.Entry<String, Object> entry = iterator.next();             result.append(entry.getKey()).append("=").append(entry.getValue()).append("&");         }          return result.substring(0, result.lastIndexOf("&"));     }      /**      * Read input stream      * @param connection Http Connection      * @return response body      * @throws IOException      */     private static String receiveResponse(HttpURLConnection connection) throws IOException {         BufferedReader reader = new BufferedReader(                 new InputStreamReader(connection.getInputStream(), "UTF-8"));         StringBuilder receivedContent = new StringBuilder(1024);         String line = "";         while((line = reader.readLine()) != null) {             receivedContent.append(line);         }         reader.close();         return receivedContent.toString();     }  } 

测试

 public class HttpSimulation {      @Test     public void testSignInFromCubeMaster() {         int userId = 5;          String url = "http://localhost:8080/cube/user/signInFromCubeMaster";          Map<String, Object> params = MapFactory.newHashMap();         params.put("userId", userId);          HttpHelper.get(url, params);      } } 

结束语

Beta版,简单请求使用没问题,难免有Bug,欢迎各路高手批评指正,代码已上传至 Github ,欢迎打星星。

原文  http://www.cnblogs.com/coderworld/p/http-simulator.html
正文到此结束
Loading...