網頁

2018/4/12

在Java傳送HTTP Request及取得Response的Cookies

在Java中傳送HTTP Request可使用java.net.HttpUrlConnection

下面範例使用POST傳送資料。

public void sendPostRequest() {
  String requestUrl = "http://example.com/post";
  String token = "token"; // 授權token
  
  String parameters = "name=matt";
  byte[] postData = parameters.getBytes(StandardCharsets.UTF_8);
  int postDataLength = postData.length;
  
  try {
    URL url = new URL(requestUrl);
    HttpURLConnection conn = (HttpURLConnection) url.openConnection();           
    conn.setDoOutput(true); // post有寫出資料所以要設為true
    conn.setInstanceFollowRedirects(false); // 不用自動重新導向所以設為false
    conn.setRequestMethod(HttpMethod.POST.name()); // POST
    conn.setRequestProperty("Authorization", token);
    conn.setRequestProperty("Content-Type", MediaType.APPLICATION_FORM_URLENCODED_VALUE); // application/x-www-form-urlencoded
    conn.setRequestProperty("charset", StandardCharsets.UTF_8.name()); // UTF-8
    conn.setRequestProperty("Content-Length", Integer.toString(postDataLength));
    conn.setUseCaches(false);
    
    // 寫出 post data
    new DataOutputStream(conn.getOutputStream()).write(postData);
    
    // 讀取 response data
    BufferedReader reader = new BufferedReader(new InputStreamReader(conn.getInputStream()));
    String inputLine;
    StringBuffer responseData = new StringBuffer();
    while ((inputLine = reader.readLine()) != null) {
      responseData.append(inputLine);
    }
    reader.close();
    System.out.println(responseData.toString()); // 印出"success"

    List cookies = conn.getHeaderFields().get("Set-Cookie"); // 取得response的cookies
    for(String s : cookies) {
      String[] cookie = s.split("=");
      if("mycookie".equalsIgnoreCase(cookie[0])) {
        System.out.println(cookie[1]); // 印出"hello_world"
      }
    }
    
  } catch(MalformedURLException e){
    e.printStackTrace();
  } catch (IOException e) {
    e.printStackTrace();
  }
  
}

下面為接收上面傳送的url的Spring Controller RequestMapping方法,並設定response的cookie。

@PostMapping(value="/post", consumes=MediaType.APPLICATION_FORM_URLENCODED_VALUE, produces=MediaType.TEXT_PLAIN_VALUE)
public String post(@RequestParam String name, HttpServletResponse response) throws IOException{
  System.out.println(name);  // 印出"matt"

  Cookie cookie = new Cookie("mycookie","hello_world");
  response.addCookie(cookie);

  return "success";
}

參考:

沒有留言:

張貼留言