Java调用HTTP接口

说明

Java调用HTTP接口可以使用Java的HttpURLConnection或HttpClient等工具

HttpURLConnection

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

public class HttpExample {
    public static void main(String[] args) throws Exception {
        // 创建URL对象
        URL url = new URL("http://example.com/api");

        // 创建HttpURLConnection对象
        HttpURLConnection conn = (HttpURLConnection) url.openConnection();

        // 设置请求方法为GET
        conn.setRequestMethod("GET");

        // 发送请求
        int responseCode = conn.getResponseCode();

        // 读取响应内容
        BufferedReader in = new BufferedReader(new InputStreamReader(conn.getInputStream()));
        String inputLine;
        StringBuffer response = new StringBuffer();
        while ((inputLine = in.readLine()) != null) {
            response.append(inputLine);
        }
        in.close();

        // 打印响应内容
        System.out.println(response.toString());
    }
}

HttpClient

import org.apache.http.HttpResponse;
import org.apache.http.client.HttpClient;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.impl.client.HttpClientBuilder;
import java.io.BufferedReader;
import java.io.InputStreamReader;

public class HttpExample {
    public static void main(String[] args) throws Exception {
        // 创建HttpClient对象
        HttpClient client = HttpClientBuilder.create().build();

        // 创建HttpGet对象
        HttpGet request = new HttpGet("http://example.com/api");

        // 发送请求
        HttpResponse response = client.execute(request);

        // 读取响应内容
        BufferedReader in = new BufferedReader(new InputStreamReader(response.getEntity().getContent()));
        String inputLine;
        StringBuffer responseBuffer = new StringBuffer();
        while ((inputLine = in.readLine()) != null) {
            responseBuffer.append(inputLine);
        }
        in.close();

        // 打印响应内容
        System.out.println(responseBuffer.toString());
    }
}

你可能感兴趣的:(java,http,开发语言)