Learning rest together (12.2) -- using rest in Java

Source: Internet
Author: User

Original address: http://rest.elkstein.org/

Learn rest: a tutorial

Send an http get request
The main class isHttpurlconnectionBy calling a URLOpenconnection can obtain this class,The signature of the openconnection method points to a super-class urlconnection. We also need to perform a downward transformation of the class type.

The following method sends a request and returns a long string:

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();}
(This code is a bit rough and requires the appropriate Try/ Catch/ Finally to ensure that the reader can be closed, and so on.Remember, if the URL contains parameters, it must be properly encoded (for example, the space is % 20, and so on ). Class Urlencoder Used for Such Encoding.

Send an http post request
The URL in the POST request also needs to be encoded, as shown in the following method:

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 properTry/Catch/FinallyStructures). 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 particle
HttpclientSet 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

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

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.