java实现Http请求

使用 HttpClient 库

HttpClient 是一个 HTTP 客户端库,提供了向 HTTP 服务器发送请求和处理响应的方法。

它支持多种请求协议,如 GET、POST 等,并允许开发者自由地设置请求头、请求参数、连接池等。HttpClient 还提供了基于线程池的异步请求处理方式。

示例代码:

package com.sdwg.module.person.controller.admin.fkyy;
 
import net.sf.json.JSONObject;
import org.apache.http.HttpEntity;
import org.apache.http.client.methods.CloseableHttpResponse;
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 cs {
    public static void main(String[] args) throws Exception {
        CloseableHttpClient httpclient = HttpClients.createDefault();
        HttpGet httpget = new HttpGet("https://www.baidu.com");
        CloseableHttpResponse response = httpclient.execute(httpget);
 
        try {
            HttpEntity entity = response.getEntity();
            String result = EntityUtils.toString(entity);
            EntityUtils.consume(entity);
            JSONObject jsonObject = JSONObject.fromObject(result);
            System.out.println(jsonObject);
            System.out.println(jsonObject.getString("openid"));
        } finally {
            response.close();
        }
    }
}

你可能感兴趣的:(http,网络协议,网络)