怎么利用Java实现调用http请求

发布时间:2022-08-23 16:52:13 作者:iii
来源:亿速云 阅读:281

怎么利用Java实现调用HTTP请求

目录

  1. 引言
  2. HTTP协议基础
  3. Java中的HTTP请求库
  4. 使用HttpURLConnection发送HTTP请求
  5. 使用Apache HttpClient发送HTTP请求
  6. 使用OkHttp发送HTTP请求
  7. 使用Spring RestTemplate发送HTTP请求
  8. 使用Java 11 HttpClient发送HTTP请求
  9. HTTP请求的常见问题与解决方案
  10. 性能优化
  11. 安全性考虑
  12. 总结

引言

在现代的Web开发中,HTTP请求是不可或缺的一部分。无论是与后端API进行通信,还是从外部服务获取数据,HTTP请求都扮演着重要的角色。Java作为一种广泛使用的编程语言,提供了多种方式来实现HTTP请求。本文将详细介绍如何使用Java中的不同库和工具来发送HTTP请求,并探讨一些常见问题和解决方案。

HTTP协议基础

HTTP请求方法

HTTP协议定义了多种请求方法,常用的有:

HTTP状态码

HTTP状态码用于表示请求的处理结果,常见的状态码有:

HTTP头部

HTTP头部包含了请求和响应的元数据,常见的头部字段有:

Java中的HTTP请求库

Java提供了多种库和工具来发送HTTP请求,常用的有:

使用HttpURLConnection发送HTTP请求

GET请求

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

public class HttpURLConnectionExample {
    public static void main(String[] args) throws Exception {
        URL url = new URL("https://jsonplaceholder.typicode.com/posts/1");
        HttpURLConnection connection = (HttpURLConnection) url.openConnection();
        connection.setRequestMethod("GET");

        int responseCode = connection.getResponseCode();
        System.out.println("Response Code: " + responseCode);

        BufferedReader in = new BufferedReader(new InputStreamReader(connection.getInputStream()));
        String inputLine;
        StringBuilder response = new StringBuilder();

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

        System.out.println("Response: " + response.toString());
    }
}

POST请求

import java.io.OutputStream;
import java.net.HttpURLConnection;
import java.net.URL;

public class HttpURLConnectionExample {
    public static void main(String[] args) throws Exception {
        URL url = new URL("https://jsonplaceholder.typicode.com/posts");
        HttpURLConnection connection = (HttpURLConnection) url.openConnection();
        connection.setRequestMethod("POST");
        connection.setRequestProperty("Content-Type", "application/json; utf-8");
        connection.setRequestProperty("Accept", "application/json");
        connection.setDoOutput(true);

        String jsonInputString = "{\"title\": \"foo\", \"body\": \"bar\", \"userId\": 1}";

        try (OutputStream os = connection.getOutputStream()) {
            byte[] input = jsonInputString.getBytes("utf-8");
            os.write(input, 0, input.length);
        }

        int responseCode = connection.getResponseCode();
        System.out.println("Response Code: " + responseCode);

        BufferedReader in = new BufferedReader(new InputStreamReader(connection.getInputStream()));
        String inputLine;
        StringBuilder response = new StringBuilder();

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

        System.out.println("Response: " + response.toString());
    }
}

设置请求头

connection.setRequestProperty("Authorization", "Bearer token");

处理响应

int responseCode = connection.getResponseCode();
if (responseCode == HttpURLConnection.HTTP_OK) {
    // 处理成功响应
} else {
    // 处理错误响应
}

使用Apache HttpClient发送HTTP请求

GET请求

import org.apache.http.HttpResponse;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClients;
import org.apache.http.util.EntityUtils;

public class HttpClientExample {
    public static void main(String[] args) throws Exception {
        CloseableHttpClient httpClient = HttpClients.createDefault();
        HttpGet request = new HttpGet("https://jsonplaceholder.typicode.com/posts/1");

        HttpResponse response = httpClient.execute(request);
        String responseBody = EntityUtils.toString(response.getEntity());

        System.out.println("Response Code: " + response.getStatusLine().getStatusCode());
        System.out.println("Response: " + responseBody);

        httpClient.close();
    }
}

POST请求

import org.apache.http.HttpResponse;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.entity.StringEntity;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClients;
import org.apache.http.util.EntityUtils;

public class HttpClientExample {
    public static void main(String[] args) throws Exception {
        CloseableHttpClient httpClient = HttpClients.createDefault();
        HttpPost request = new HttpPost("https://jsonplaceholder.typicode.com/posts");

        String jsonInputString = "{\"title\": \"foo\", \"body\": \"bar\", \"userId\": 1}";
        request.setEntity(new StringEntity(jsonInputString));
        request.setHeader("Content-Type", "application/json; utf-8");
        request.setHeader("Accept", "application/json");

        HttpResponse response = httpClient.execute(request);
        String responseBody = EntityUtils.toString(response.getEntity());

        System.out.println("Response Code: " + response.getStatusLine().getStatusCode());
        System.out.println("Response: " + responseBody);

        httpClient.close();
    }
}

设置请求头

request.setHeader("Authorization", "Bearer token");

处理响应

int statusCode = response.getStatusLine().getStatusCode();
if (statusCode == 200) {
    // 处理成功响应
} else {
    // 处理错误响应
}

使用OkHttp发送HTTP请求

GET请求

import okhttp3.OkHttpClient;
import okhttp3.Request;
import okhttp3.Response;

public class OkHttpExample {
    public static void main(String[] args) throws Exception {
        OkHttpClient client = new OkHttpClient();

        Request request = new Request.Builder()
                .url("https://jsonplaceholder.typicode.com/posts/1")
                .build();

        try (Response response = client.newCall(request).execute()) {
            System.out.println("Response Code: " + response.code());
            System.out.println("Response: " + response.body().string());
        }
    }
}

POST请求

import okhttp3.MediaType;
import okhttp3.OkHttpClient;
import okhttp3.Request;
import okhttp3.RequestBody;
import okhttp3.Response;

public class OkHttpExample {
    public static void main(String[] args) throws Exception {
        OkHttpClient client = new OkHttpClient();

        MediaType JSON = MediaType.parse("application/json; charset=utf-8");
        String jsonInputString = "{\"title\": \"foo\", \"body\": \"bar\", \"userId\": 1}";
        RequestBody body = RequestBody.create(jsonInputString, JSON);

        Request request = new Request.Builder()
                .url("https://jsonplaceholder.typicode.com/posts")
                .post(body)
                .build();

        try (Response response = client.newCall(request).execute()) {
            System.out.println("Response Code: " + response.code());
            System.out.println("Response: " + response.body().string());
        }
    }
}

设置请求头

Request request = new Request.Builder()
        .url("https://jsonplaceholder.typicode.com/posts/1")
        .header("Authorization", "Bearer token")
        .build();

处理响应

int statusCode = response.code();
if (statusCode == 200) {
    // 处理成功响应
} else {
    // 处理错误响应
}

使用Spring RestTemplate发送HTTP请求

GET请求

import org.springframework.web.client.RestTemplate;

public class RestTemplateExample {
    public static void main(String[] args) {
        RestTemplate restTemplate = new RestTemplate();
        String url = "https://jsonplaceholder.typicode.com/posts/1";

        String response = restTemplate.getForObject(url, String.class);
        System.out.println("Response: " + response);
    }
}

POST请求

import org.springframework.http.HttpEntity;
import org.springframework.http.HttpHeaders;
import org.springframework.http.MediaType;
import org.springframework.web.client.RestTemplate;

public class RestTemplateExample {
    public static void main(String[] args) {
        RestTemplate restTemplate = new RestTemplate();
        String url = "https://jsonplaceholder.typicode.com/posts";

        HttpHeaders headers = new HttpHeaders();
        headers.setContentType(MediaType.APPLICATION_JSON);

        String jsonInputString = "{\"title\": \"foo\", \"body\": \"bar\", \"userId\": 1}";
        HttpEntity<String> request = new HttpEntity<>(jsonInputString, headers);

        String response = restTemplate.postForObject(url, request, String.class);
        System.out.println("Response: " + response);
    }
}

设置请求头

HttpHeaders headers = new HttpHeaders();
headers.set("Authorization", "Bearer token");

处理响应

ResponseEntity<String> response = restTemplate.getForEntity(url, String.class);
int statusCode = response.getStatusCodeValue();
if (statusCode == 200) {
    // 处理成功响应
} else {
    // 处理错误响应
}

使用Java 11 HttpClient发送HTTP请求

GET请求

import java.net.URI;
import java.net.http.HttpClient;
import java.net.http.HttpRequest;
import java.net.http.HttpResponse;

public class HttpClientExample {
    public static void main(String[] args) throws Exception {
        HttpClient client = HttpClient.newHttpClient();
        HttpRequest request = HttpRequest.newBuilder()
                .uri(URI.create("https://jsonplaceholder.typicode.com/posts/1"))
                .build();

        HttpResponse<String> response = client.send(request, HttpResponse.BodyHandlers.ofString());

        System.out.println("Response Code: " + response.statusCode());
        System.out.println("Response: " + response.body());
    }
}

POST请求

import java.net.URI;
import java.net.http.HttpClient;
import java.net.http.HttpRequest;
import java.net.http.HttpResponse;
import java.net.http.HttpRequest.BodyPublishers;

public class HttpClientExample {
    public static void main(String[] args) throws Exception {
        HttpClient client = HttpClient.newHttpClient();
        String jsonInputString = "{\"title\": \"foo\", \"body\": \"bar\", \"userId\": 1}";

        HttpRequest request = HttpRequest.newBuilder()
                .uri(URI.create("https://jsonplaceholder.typicode.com/posts"))
                .header("Content-Type", "application/json; utf-8")
                .header("Accept", "application/json")
                .POST(BodyPublishers.ofString(jsonInputString))
                .build();

        HttpResponse<String> response = client.send(request, HttpResponse.BodyHandlers.ofString());

        System.out.println("Response Code: " + response.statusCode());
        System.out.println("Response: " + response.body());
    }
}

设置请求头

HttpRequest request = HttpRequest.newBuilder()
        .uri(URI.create("https://jsonplaceholder.typicode.com/posts/1"))
        .header("Authorization", "Bearer token")
        .build();

处理响应

int statusCode = response.statusCode();
if (statusCode == 200) {
    // 处理成功响应
} else {
    // 处理错误响应
}

HTTP请求的常见问题与解决方案

超时设置

在发送HTTP请求时,设置合理的超时时间是非常重要的,以防止请求长时间挂起。

// HttpURLConnection
connection.setConnectTimeout(5000);
connection.setReadTimeout(5000);

// Apache HttpClient
RequestConfig config = RequestConfig.custom()
        .setConnectTimeout(5000)
        .setSocketTimeout(5000)
        .build();
CloseableHttpClient httpClient = HttpClients.custom()
        .setDefaultRequestConfig(config)
        .build();

// OkHttp
OkHttpClient client = new OkHttpClient.Builder()
        .connectTimeout(5, TimeUnit.SECONDS)
        .readTimeout(5, TimeUnit.SECONDS)
        .build();

// Spring RestTemplate
RestTemplate restTemplate = new RestTemplate();
restTemplate.setRequestFactory(new HttpComponentsClientHttpRequestFactory());
HttpComponentsClientHttpRequestFactory factory = (HttpComponentsClientHttpRequestFactory) restTemplate.getRequestFactory();
factory.setConnectTimeout(5000);
factory.setReadTimeout(5000);

// Java 11 HttpClient
HttpClient client = HttpClient.newBuilder()
        .connectTimeout(Duration.ofSeconds(5))
        .build();

重试机制

在某些情况下,请求可能会失败,设置重试机制可以提高请求的成功率。

// Apache HttpClient
HttpRequestRetryHandler retryHandler = new DefaultHttpRequestRetryHandler(3, true);
CloseableHttpClient httpClient = HttpClients.custom()
        .setRetryHandler(retryHandler)
        .build();

// OkHttp
OkHttpClient client = new OkHttpClient.Builder()
        .retryOnConnectionFailure(true)
        .build();

代理设置

在某些网络环境下,可能需要通过代理服务器发送HTTP请求。

// HttpURLConnection
Proxy proxy = new Proxy(Proxy.Type.HTTP, new InetSocketAddress("proxy.example.com", 8080));
HttpURLConnection connection = (HttpURLConnection) url.openConnection(proxy);

// Apache HttpClient
HttpHost proxy = new HttpHost("proxy.example.com", 8080);
RequestConfig config = RequestConfig.custom()
        .setProxy(proxy)
        .build();
CloseableHttpClient httpClient = HttpClients.custom()
        .setDefaultRequestConfig(config)
        .build();

// OkHttp
Proxy proxy = new Proxy(Proxy.Type.HTTP, new InetSocketAddress("proxy.example.com", 8080));
OkHttpClient client = new OkHttpClient.Builder()
        .proxy(proxy)
        .build();

// Spring RestTemplate
SimpleClientHttpRequestFactory requestFactory = new SimpleClientHttpRequestFactory();
requestFactory.setProxy(new Proxy(Proxy.Type.HTTP, new InetSocketAddress("proxy.example.com", 8080)));
RestTemplate restTemplate = new RestTemplate(requestFactory);

// Java 11 HttpClient
ProxySelector proxySelector = new ProxySelector() {
    @Override
    public List<Proxy> select(URI uri) {
        return Arrays.asList(new Proxy(Proxy.Type.HTTP, new InetSocketAddress("proxy.example.com", 8080)));
    }

    @Override
    public void connectFailed(URI uri, SocketAddress sa, IOException ioe) {
        // 处理连接失败
    }
};
HttpClient client = HttpClient.newBuilder()
        .proxy(proxySelector)
        .build();

SSL/TLS配置

在发送HTTPS请求时,可能需要配置SSL/TLS以处理证书问题。

”`java // HttpURLConnection HttpsURLConnection.setDefaultSSLSocketFactory(sslContext.getSocketFactory());

// Apache HttpClient SSLContext sslContext = SSLContexts.custom() .loadTrustMaterial(new TrustSelfSignedStrategy()) .build

推荐阅读:
  1. 手动发送HTTP请求调用和异步调用WebService
  2. python利用requests模拟http请求及请求头

免责声明:本站发布的内容(图片、视频和文字)以原创、转载和分享为主,文章观点不代表本网站立场,如果涉及侵权请联系站长邮箱:is@yisu.com进行举报,并提供相关证据,一经查实,将立刻删除涉嫌侵权内容。

java http

上一篇:js如何实现登录弹框

下一篇:Vue子组件props怎么从父组件接收数据并存入data

相关阅读

您好,登录后才能下订单哦!

密码登录
登录注册
其他方式登录
点击 登录注册 即表示同意《亿速云用户服务条款》