JAVA 인터넷 12.2. Using REST in Java

2015.07.16 21:23

졸리운_곰 조회 수:127

12.2. Using REST in Java

 

 

Issuing HTTP GET Requests
The key class here is HttpURLConnection, obtained by invoking openConnection on a URL object. Sadly, openConnection method's signature specifies that it returns the superclass type, URLConnection, and we have to downcast the result.

The following method issues a request and returns the entire response as one 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 very raw; it should be properly padded with try/catch/finally blocks to ensure the reader is closed, etc.)

Remember that if the request URL includes parameters, they must be properly encoded (e.g., a space is %20, etc.). The class URLEncoder can be used to perform this encoding.

Issuing HTTP POST Requests
URL encoding is also required for POST requests, as shown in the following method:

경축! 아무것도 안하여 에스천사게임즈가 새로운 모습으로 재오픈 하였습니다.
어린이용이며, 설치가 필요없는 브라우저 게임입니다.
https://s1004games.com

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 sight (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 as caching.

 

 

 

[출처] http://rest.elkstein.org/2008/02/using-rest-in-java.html

 

본 웹사이트는 광고를 포함하고 있습니다.
광고 클릭에서 발생하는 수익금은 모두 웹사이트 서버의 유지 및 관리, 그리고 기술 콘텐츠 향상을 위해 쓰여집니다.
번호 제목 글쓴이 날짜 조회 수
169 Spring Batch Example 1 - Spring Batch란? file 졸리운_곰 2020.10.24 127
» 12.2. Using REST in Java 졸리운_곰 2015.07.16 127
167 Spring Batch Multithreading Example file 졸리운_곰 2019.01.31 126
166 SWT: Respond to Long Running Tasks 졸리운_곰 2015.11.07 126
165 Creating a TreeViewer 졸리운_곰 2015.08.06 126
164 Java Console and File Input/Output Cheat Sheet 졸리운_곰 2015.07.05 126
163 SpringBoot JPA 예제(@OneToMany, 단방향) 졸리운_곰 2018.12.31 125
162 SWT Paint Example : 2D « SWT JFace Eclipse « Java 졸리운_곰 2015.07.28 125
161 [java maven] jar 파일 의존성 한번에 다운로드 maven 사용 졸리운_곰 2023.08.18 124
160 스프링(Spring) 프레임워크 기본 개념 강좌 (6) - Dynamic Proxy 졸리운_곰 2017.10.02 124
159 Spring Batch Example 3 - 청크 지향 프로세싱 file 졸리운_곰 2020.10.24 123
158 [스프링] 스프링 배치 기본 개념 file 졸리운_곰 2019.12.24 123
157 Springboot 에서 DATA-JPA(Hibernate) 사용하기[3] - JOIN file 졸리운_곰 2018.09.18 123
156 Demonstrates a Canvas : Canvas « SWT JFace Eclipse « Java file 졸리운_곰 2015.07.28 123
155 ESE2006-EclipseModelingSymposium15_GMF.pdf file 졸리운_곰 2019.09.21 122
154 Create TreeView based on your own tree node structure : TreeViewer « SWT « Java Tutorial 졸리운_곰 2015.08.05 122
153 [java 인공지능] 자바를 위한 머신 러닝 라이브러리 졸리운_곰 2023.08.27 121
152 Eclipse RAP Tutorial for Beginners - Workbench Application (OLD) file 졸리운_곰 2021.01.30 121
151 MongoBatis Ver 1.04 in SpringFrameWork (mongoDB + MyBatis) file 졸리운_곰 2020.09.21 121
150 [Java] 효율적인 JUnit 사용 방법과 유용한 팁 file 졸리운_곰 2022.10.20 120
대표 김성준 주소 : 경기 용인 분당수지 U타워 등록번호 : 142-07-27414
통신판매업 신고 : 제2012-용인수지-0185호 출판업 신고 : 수지구청 제 123호 개인정보보호최고책임자 : 김성준 sjkim70@stechstar.com
대표전화 : 010-4589-2193 [fax] 02-6280-1294 COPYRIGHT(C) stechstar.com ALL RIGHTS RESERVED