Java实现HTTP请求

一、利用RestTemplate来实现

RestTemplate是spring-web封装的一个请求类,基本可以满足一般业务需求。

private static RestTemplate restTemplate = new RestTemplate();
public static final HttpHeaders jsonAndXml;

    static {
        jsonAndXml = new HttpHeaders();
        jsonAndXml.setContentType(MediaType.APPLICATION_JSON_UTF8);
        List<MediaType> mediaTypeList = new ArrayList<MediaType>();
        mediaTypeList.add(MediaType.APPLICATION_XML);
        jsonAndXml.setAccept(mediaTypeList);
    }
>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>
String response = restTemplate.exchange(url, HttpMethod.GET, new HttpEntity<>(jsonAndXml), String.class).getBody();

除了exchange外,RestTemplate有许多可供开发者调用的接口,如传路径变量,参数等。

二、利用apache httpcomponents组件实现

1.导包

<dependency>
    <groupId>org.apache.httpcomponents</groupId>
    <artifactId>httpclient</artifactId>
    <version>4.5.1</version>
</dependency>

2.实现

HttpEntity body = new StringEntity(new Gson().toJson(root), ContentType.create("application/json", Consts.UTF_8));

DefaultBHttpClientConnection conn = null;
        try {
            HttpProcessor httpProcessor = HttpProcessorBuilder.create().add(new RequestContent()).add(new RequestTargetHost()).add(new RequestConnControl())
                                                              .add(new RequestUserAgent("Test/1.1")).add(new RequestExpectContinue(true)).build();
            HttpRequestExecutor httpRequestExecutor = new HttpRequestExecutor();

            HttpCoreContext coreContext = new HttpCoreContext();

            HttpHost host = new HttpHost(HOST, PORT);

            coreContext.setTargetHost(host);

            conn = new DefaultBHttpClientConnection(8 * 1024);

            ConnectionReuseStrategy connectionReuseStrategy = DefaultConnectionReuseStrategy.INSTANCE;

                if (!conn.isOpen()) {
                    Socket socket = new Socket(host.getHostName(), host.getPort());
                    conn.bind(socket);
                }

                BasicHttpEntityEnclosingRequest request = new BasicHttpEntityEnclosingRequest("POST", url);
                request.setEntity(body);

                System.out.println("URL:" + request.getRequestLine().getUri());

                httpRequestExecutor.preProcess(request, httpProcessor, coreContext);

                HttpResponse response = httpRequestExecutor.execute(request, conn, coreContext);

                httpRequestExecutor.postProcess(response, httpProcessor, coreContext);

                System.out.println("响应:" + response.getStatusLine());
                System.out.println("响应的body" + EntityUtils.toString(response.getEntity()));
                System.out.println("====结束====");

                if (!connectionReuseStrategy.keepAlive(response, coreContext)) conn.close();
                else System.out.println("保持链接");


        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            try {
                conn.close();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
Java中,有多种方式可以实现HTTP请求。其中一种常见的方式是使用Java标准库中的HttpURLConnection类。这个类提供了发送HTTP请求和接收HTTP响应的功能。你可以使用HttpURLConnection类创建连接,并设置请求方法、请求头、请求体等,然后发送请求并获取响应。具体的代码可以参考以下示例: ``` import java.io.IOException; import java.io.InputStream; import java.net.HttpURLConnection; import java.net.URL; public class HttpExample { public static void main(String[] args) throws IOException { URL url = new URL("https://www.example.com"); HttpURLConnection connection = (HttpURLConnection) url.openConnection(); connection.setRequestMethod("GET"); // 设置请求方法,例如GET、POST等 connection.setConnectTimeout(5000); // 设置连接超时时间 connection.setReadTimeout(5000); // 设置读取超时时间 int responseCode = connection.getResponseCode(); // 获取响应码 if (responseCode == HttpURLConnection.HTTP_OK) { InputStream inputStream = connection.getInputStream(); // 处理响应数据 } else { // 处理错误情况 } connection.disconnect(); // 断开连接 } } ``` 另外,你还可以使用第三方库来简化HTTP请求的过程,比如OkHttp和Spring的RestTemplate。使用OkHttp时,你可以创建一个OkHttpClient实例,并使用Request类来构建请求,然后发送请求并获取响应。以下是一个使用OkHttp的示例代码: ``` import okhttp3.OkHttpClient; import okhttp3.Request; import okhttp3.Response; import java.io.IOException; public class OkHttpExample { private static final OkHttpClient client = new OkHttpClient(); public static void main(String[] args) throws IOException { Request request = new Request.Builder() .url("https://www.example.com") .build(); try (Response response = client.newCall(request).execute()) { String result = response.body().string(); System.out.println(result); } } } ``` 如果你使用Spring框架,你可以使用RestTemplate类来发送HTTP请求。RestTemplate封装了HTTP请求的各种方法,让你可以更方便地发送请求和处理响应。以下是一个使用RestTemplate的示例代码: ``` import org.springframework.http.ResponseEntity; import org.springframework.web.client.RestTemplate; public class RestTemplateExample { public static void main(String[] args) { RestTemplate restTemplate = new RestTemplate(); ResponseEntity<String> response = restTemplate.getForEntity("https://www.example.com", String.class); String result = response.getBody(); System.out.println(result); } } ``` 以上是三种常见的Java实现HTTP请求的方法,你可以根据具体的需求选择适合的方式来发送HTTP请求。<span class="em">1</span><span class="em">2</span><span class="em">3</span> #### 引用[.reference_title] - *1* *2* *3* [Java 实现HTTP请求的四种方式总结](https://blog.csdn.net/qq_34383510/article/details/130627924)[target="_blank" data-report-click={"spm":"1018.2226.3001.9630","extra":{"utm_source":"vip_chatgpt_common_search_pc_result","utm_medium":"distribute.pc_search_result.none-task-cask-2~all~insert_cask~default-1-null.142^v93^chatsearchT3_1"}}] [.reference_item style="max-width: 100%"] [ .reference_list ]
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值