1. 程式人生 > >HttpURLConnection 訪問伺服器介面

HttpURLConnection 訪問伺服器介面

1,客戶端請求工具類

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.OutputStreamWriter;
import java.net.HttpURLConnection;
import java.net.URL;
import java.util.Map;

/** 
 * Http請求工具類 
 * 
 */
public class HttpRequestUtil {

  public String submitPostData(String strUrlPath, Map<String, String> params) {
    String postData = getRequestData(params, "utf-8").toString();// 獲得請求體
    try {
      // 傳送POST請求
      URL url = new URL(strUrlPath);
      HttpURLConnection conn = (HttpURLConnection) url.openConnection();
      conn.setRequestProperty("User-Agent", "Mozilla/4.0 (compatible; MSIE 5.0; Windows NT; DigExt)");
      conn.setRequestMethod("POST");
      // conn.setRequestProperty("Content-Type", "application/json");
      conn.setRequestProperty("Content-Type", "application/x-www-form-urlencoded");
      conn.setRequestProperty("Connection", "Keep-Alive");
      conn.setUseCaches(false);
      conn.setDoOutput(true);
      conn.setRequestProperty("Content-Length", "" + postData.length());
      OutputStreamWriter out = new OutputStreamWriter(conn.getOutputStream(), "UTF-8");
      out.write(postData);
      out.flush();
      out.close();
      // 獲取響應狀態
      if (conn.getResponseCode() != HttpURLConnection.HTTP_OK) {
        System.out.println("connect failed!" + conn.getResponseCode());
        return "";
      }
      // 獲取響應內容體
      String line, result = "";
      BufferedReader in = new BufferedReader(new InputStreamReader(conn.getInputStream(), "utf-8"));
      while ((line = in.readLine()) != null) {
        result += line + "\n";
      }
      in.close();
      return result;
    } catch (IOException e) {
      e.printStackTrace(System.out);
    }
    return "";
  }

  /*
   * Function : 封裝請求體資訊 Param : params請求體內容,encode編碼格式
   */
  public static StringBuffer getRequestData(Map<String, String> params, String encode) {
    StringBuffer stringBuffer = new StringBuffer(); // 儲存封裝好的請求體資訊
    try {
      for (Map.Entry<String, String> entry : params.entrySet()) {
        stringBuffer.append(entry.getKey()).append("=").append(entry.getValue()).append("&");
      }
      stringBuffer.deleteCharAt(stringBuffer.length() - 1); // 刪除最後的一個"&"
    } catch (Exception e) {
      e.printStackTrace();
    }
    return stringBuffer;
  }
}

2,具體請求

      HttpRequestUtil util = new HttpRequestUtil();
      String url = "需要訪問的介面";
      //map引數
      Map<String, String> paramMap = new HashMap<>();
      paramMap.put("1", 1);
      paramMap.put("2", 2);
      paramMap.put("3", 3);
      util.submitPostData(url, paramMap);

3,伺服器端介面

@RequestMapping(value = "saveData", method = RequestMethod.POST)
  @ResponseBody
  public ErrorObject saveData(HttpServletRequest request, HttpServletResponse response) throws Exception {
    //方法一
    String roomStr = request.getParameter("1");
    String areaStr = request.getParameter("2");
    String dictionaryStr = request.getParameter("3");
    object object= JSON.parseObject(1, object.class);
    return tblRoomsService.save(object);
    //方法二
    // request.setCharacterEncoding("UTF-8");
    // BufferedReader br = new BufferedReader(new
    // InputStreamReader(request.getInputStream(), "utf-8"));
    // String line = "";
    // String paramStr = "";
    // while (null != (line = br.readLine())) {
    // paramStr += line;
    // }

  }