一起來學REST(12.2)——Java中使用REST

來源:互聯網
上載者:User

 原文地址:http://rest.elkstein.org/

Learn REST: A Tutorial

發送HTTP GET請求
主要的類是HttpURLConnection,通過對一個URL調用openConnection可以得到這個類,openConnection方法的簽名指向一個超類URLConnection,我們還需要對其進行類類型向下轉型。

下面的方法發送一個請求,並且返回一個長字串:

public static String httpGet(String urlStr) throws IOException {  URL url = new URL(urlStr);  HttpURLConnection conn =      (HttpURLConnection) url.openConnection();  if (conn.getResponseCode() != 200) {    throw new IOException(conn.getResponseMessage());  }  // Buffer the result into a string  BufferedReader rd = new BufferedReader(      new InputStreamReader(conn.getInputStream()));  StringBuilder sb = new StringBuilder();  String line;  while ((line = rd.readLine()) != null) {    sb.append(line);  }  rd.close();  conn.disconnect();  return sb.toString();}
(這段代碼有些粗糙,需要加上適當的try/catch/finally來保證reader可以關閉,等等。記住,如果URL包含參數,必須進行適當的編碼(例如空格是%20,等等)。類URLEncoder用來進行這樣的編碼。

發送HTTP POST請求
在POST請求中的URL也需要編碼,如下面的方法所示:

public static String httpPost(String urlStr, String[] paramName,String[] paramVal) throws Exception {  URL url = new URL(urlStr);  HttpURLConnection conn =      (HttpURLConnection) url.openConnection();  conn.setRequestMethod("POST");  conn.setDoOutput(true);  conn.setDoInput(true);  conn.setUseCaches(false);  conn.setAllowUserInteraction(false);  conn.setRequestProperty("Content-Type",      "application/x-www-form-urlencoded");  // Create the form content  OutputStream out = conn.getOutputStream();  Writer writer = new OutputStreamWriter(out, "UTF-8");  for (int i = 0; i < paramName.length; i++) {    writer.write(paramName[i]);    writer.write("=");    writer.write(URLEncoder.encode(paramVal[i], "UTF-8"));    writer.write("&");  }  writer.close();  out.close();  if (conn.getResponseCode() != 200) {    throw new IOException(conn.getResponseMessage());  }  // Buffer the result into a string  BufferedReader rd = new BufferedReader(      new InputStreamReader(conn.getInputStream()));  StringBuilder sb = new StringBuilder();  String line;  while ((line = rd.readLine()) != null) {    sb.append(line);  }  rd.close();  conn.disconnect();  return sb.toString();}

As you can see, it's not a pretty site (and that's before adding proper try/catch/finally structures). The problem is that, out of the box, Java's support for handling web connections is pretty low-level.

A good solution can be found in the popular
Apache Commons library, and in particular the
httpclient set of packages. See
Yahoo! guide to REST with Java for details and examples. The documentation covers several interesting extras, such ascaching.

By Dr. M. Elkstein

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.