java调用Restful接口的三种方法

  • Post category:http

下面我将为您详细讲解Java调用Restful接口的三种方法。

1. 使用Java的HttpURLConnection类

Java中提供了HttpURLConnection类来实现Http协议的请求和响应。使用该类发送Restful请求的步骤如下:

  1. 创建一个URL对象,其中包含了请求的url和一些可选参数
  2. 打开连接并指定请求方法和一些可选参数
  3. 添加请求头信息(可选)
  4. 写入请求体信息(可选)
  5. 发送请求,并读取响应内容
  6. 关闭连接

以下是一个使用HttpURLConnection类发送GET请求的示例:

import java.net.HttpURLConnection;
import java.net.URL;
import java.io.BufferedReader;
import java.io.InputStreamReader;

public class HttpURLConnectionExample {

    private final String USER_AGENT = "Mozilla/5.0";

    public static void main(String[] args) throws Exception {

        HttpURLConnectionExample http = new HttpURLConnectionExample();

        System.out.println("Testing 1 - Send Http GET request");
        http.sendGet();

    }

    // HTTP GET request
    private void sendGet() throws Exception {

        String url = "http://localhost:8080/api/v1/users/1";

        URL obj = new URL(url);
        HttpURLConnection con = (HttpURLConnection) obj.openConnection();

        // optional default is GET
        con.setRequestMethod("GET");

        //add request header
        con.setRequestProperty("User-Agent", USER_AGENT);

        int responseCode = con.getResponseCode();
        System.out.println("\nSending 'GET' request to URL : " + url);
        System.out.println("Response Code : " + responseCode);

        BufferedReader in = new BufferedReader(
                new InputStreamReader(con.getInputStream()));
        String inputLine;
        StringBuffer response = new StringBuffer();

        while ((inputLine = in.readLine()) != null) {
            response.append(inputLine);
        }
        in.close();

        //print result
        System.out.println(response.toString());

    }

}

2. 使用Java的Apache Httpclient类

Apache Httpclient是一个开源的Java HttpClient库,用来处理Http请求和响应。使用该类发送Restful请求的步骤如下:

  1. 创建一个HttpClient实例
  2. 创建一个请求对象,设置请求方法和url,并添加一些Header信息和参数
  3. 执行请求并获取响应
  4. 从响应中获取返回的状态码、头信息和响应数据

以下是一个使用Httpclient类发送POST请求的示例:

import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.client.HttpClient;
import org.apache.http.client.entity.UrlEncodedFormEntity;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.message.BasicNameValuePair;
import org.apache.http.util.EntityUtils;

import java.io.IOException;
import java.util.ArrayList;
import java.util.List;

public class HttpclientExample {

    public static void main(String[] args) {
        HttpClient httpClient = new DefaultHttpClient();
        HttpPost post = new HttpPost("http://localhost:8080/api/v1/users");
        List<BasicNameValuePair> params = new ArrayList<BasicNameValuePair>();
        params.add(new BasicNameValuePair("name", "John"));
        params.add(new BasicNameValuePair("age", "30"));
        try {
            post.setEntity(new UrlEncodedFormEntity(params, "UTF-8"));
            HttpResponse response = httpClient.execute(post);
            HttpEntity entity = response.getEntity();
            System.out.println(EntityUtils.toString(entity, "UTF-8"));
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

}

3. 使用Java的Spring RestTemplate类

Spring RestTemplate是一个基于Http协议的Rest客户端,提供了简单而全面的Restful客户端支持。使用该类发送Restful请求的步骤如下:

  1. 创建一个RestTemplate实例
  2. 构建请求参数和请求头信息
  3. 发送请求并获取响应对象
  4. 从响应对象中获取返回的状态码、头信息和响应数据

以下是一个使用RestTemplate类发送PUT请求的示例:

import org.springframework.http.HttpHeaders;
import org.springframework.http.HttpMethod;
import org.springframework.http.MediaType;
import org.springframework.http.ResponseEntity;
import org.springframework.web.client.RestTemplate;

public class RestTemplateExample {

    public static void main(String[] args) {
        RestTemplate restTemplate = new RestTemplate();
        HttpHeaders headers = new HttpHeaders();
        headers.setContentType(MediaType.APPLICATION_JSON);
        String url = "http://localhost:8080/api/v1/users/1";
        String jsonString = "{\"name\":\"John\",\"age\":30}";
        ResponseEntity<String> response
                = restTemplate.exchange(url, HttpMethod.PUT, new HttpEntity<String>(jsonString, headers), String.class);
        System.out.println(response.getBody());
    }

}

希望这份攻略能够对您有所帮助。