项目作者: fefong

项目描述 :
Consuming REST API with JAVA
高级语言: Java
项目地址: git://github.com/fefong/java_consumeREST.git
创建时间: 2020-04-24T18:53:44Z
项目社区:https://github.com/fefong/java_consumeREST

开源协议:

下载


Java Consume REST API

Description: Java Consume REST API (GET/POST/PUT/DELETE)

Imports

  1. import java.io.BufferedReader;
  2. import java.io.IOException;
  3. import java.io.InputStreamReader;
  4. import java.io.OutputStreamWriter;
  5. import java.net.HttpURLConnection;
  6. import java.net.MalformedURLException;
  7. import java.net.URL;

Url Connection

:warning: Need add throws declaration or surround with try/catch;

  1. URL url = new URL(String);
  2. HttpURLConnection conn = (HttpURLConnection) url.openConnection();

Sets the general request property. If a property with the key already exists, overwrite its value with the new value.

RequestMethod:

  • GET;
  • POST;
  • PUT;
  • DELETE;
  1. conn.setRequestProperty("Accept", "application/json");
  2. conn.setRequestProperty("Content-Type", "application/json");
  3. conn.setRequestMethod("POST");

To enable Output (Request Body) setting: true

:warning: If your request requires a body, the default RequestMethod is POST;

  1. conn.setDoOutput(true);

To enable Output (Response Body) setting: true

  1. conn.setDoInput(true);

When a request requires a body (request Body) it is necessary to use OutputStreamWriter to send the data.

  1. OutputStreamWriter output = new OutputStreamWriter(conn.getOutputStream());
  2. output.write(resquestBody.toString());
  3. output.flush();

Gets the status code from an HTTP response message.

  1. conn.getResponseCode()
  2. conn.getResponseMessage()

Output

Status: 200 - OK

When a request receives a body (response Body), it is necessary to use the InputStreamReader to receive the data.

  1. InputStreamReader input = new InputStreamReader(conn.getInputStream());
  2. BufferedReader br = new BufferedReader(input);
  3. String line = null;
  4. StringBuilder responseBody = new StringBuilder();
  5. responseBody.append("responseBody:\n");
  6. while ((line = br.readLine()) != null) {
  7. responseBody.append("\t" + line + "\n");
  8. }

When finished, just disconnect the connection.

  1. conn.disconnect();

Code snippet

Code;

Exceptions

  • MalformedURLException
  • IOException