1. 程式人生 > >如何在Java客戶端呼叫RESTful服務

如何在Java客戶端呼叫RESTful服務

在這個例子中,我們將看到如何使用java.net包實用工具,建立一個訪問REST服務RESTful的客戶端。當然這不是建立一個RESTful客戶端最簡單的方法,因為你必須自己讀取伺服器端的響應,以及Json和Java物件的轉換。

請求Get

public class JavaNetURLRESTFulClient {

       private static final String targetURL = "http://localhost:8080/JerseyJSONExample/rest/jsonServices/print/Jamie";

       public static void main(String[] args) {

                try {

                     URL restServiceURL = new URL(targetURL);

                     HttpURLConnection httpConnection = (HttpURLConnection) restServiceURL.openConnection();                      httpConnection.setRequestMethod("GET");                      httpConnection.setRequestProperty("Accept", "application/json");

                     if (httpConnection.getResponseCode() != 200) {                             throw new RuntimeException("HTTP GET Request Failed with Error code : "                                           + httpConnection.getResponseCode());                      }

                     BufferedReader responseBuffer = new BufferedReader(new InputStreamReader(                             (httpConnection.getInputStream())));

                     String output;                      System.out.println("Output from Server:  \n");

                     while ((output = responseBuffer.readLine()) != null) {                             System.out.println(output);                      }

                     httpConnection.disconnect();

                } catch (MalformedURLException e) {

                     e.printStackTrace();

                } catch (IOException e) {

                     e.printStackTrace();

                }

              } }

執行後輸出結果是:

Output from Server:      {"id":1,"firstName":"Jamie","age":22,"lastName":"Diaz"}

POST提交:

public class JavaNetURLRESTFulClient {

       private static final String targetURL = "http://localhost:8080/JerseyJSONExample/rest/jsonServices/send";

       public static void main(String[] args) {

              try {

                     URL targetUrl = new URL(targetURL);

                     HttpURLConnection httpConnection = (HttpURLConnection) targetUrl.openConnection();                      httpConnection.setDoOutput(true);                      httpConnection.setRequestMethod("POST");                      httpConnection.setRequestProperty("Content-Type", "application/json");

                     String input = "{\"id\":1,\"firstName\":\"Liam\",\"age\":22,\"lastName\":\"Marco\"}";

                     OutputStream outputStream = httpConnection.getOutputStream();                      outputStream.write(input.getBytes());                      outputStream.flush();

                     if (httpConnection.getResponseCode() != 200) {                             throw new RuntimeException("Failed : HTTP error code : "                                    + httpConnection.getResponseCode());                      }

                     BufferedReader responseBuffer = new BufferedReader(new InputStreamReader(                                    (httpConnection.getInputStream())));

                     String output;                      System.out.println("Output from Server:\n");                      while ((output = responseBuffer.readLine()) != null) {                             System.out.println(output);                      }

                     httpConnection.disconnect();

                } catch (MalformedURLException e) {

                     e.printStackTrace();

                } catch (IOException e) {

                     e.printStackTrace();

               }

              }      }