Java 实现HTTP请求的方式总结

1.HttpURLConnection  java原生

Java中用于进行HTTP通信的类,它预先定义了一些方法,如 setRequestMethod()、setRequestProperty() 和 getResponseCode(),方便开发者自由地控制请求和响应

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.net.HttpURLConnection;
import java.net.URL;
import java.net.URLEncoder;
import java.nio.charset.StandardCharsets;

public class HttpURLConnectionExample {
    public static void main(String[] args) {
        try {
            // 创建URL对象,附加参数到查询字符串中  GET
            String urlString = "https://api.example.com/data?param1=" + URLEncoder.encode("value1", StandardCharsets.UTF_8)
                    + "&param2=" + URLEncoder.encode("value2", StandardCharsets.UTF_8);
            URL url = new URL(urlString);
            // 打开连接
            HttpURLConnection connection = (HttpURLConnection) url.openConnection();
  /** 设置通用的请求属性
            connection.setRequestProperty("accept", "*/*");
            connection.setRequestProperty("connection", "Keep-Alive");
            connection.setRequestProperty("Content-Type","application/json;charset=utf-8");
            connection.setRequestProperty("user-agent",
            	"Mozilla/4.0 (compatible; MSIE 6.0; Windows NT 5.1;SV1)");

**/
            // 设置请求方法为GET
            connection.setRequestMethod("GET");
            // 发送请求并获取响应码...
            int responseCode = connection.getResponseCode();
            // 判断响应码
            if (responseCode == HttpURLConnection.HTTP_OK) {
                // 读取响应内容
                BufferedReader reader = new BufferedReader(new InputStreamReader(connection.getInputStream()));
                String line;
                StringBuilder response = new StringBuilder();
                while ((line = reader.readLine()) != null) {
                    response.append(line);
                }
                reader.close();

                // 处理响应内容
                System.out.println(response.toString());
            } else {
                // 处理错误情况
                System.out.println("Request failed. Response code: " + responseCode);
            }

            // 关闭连接
            connection.disconnect();
        } catch (IOException e) {
            e.printStackTrace();
        }

//==================================================================================
            // 创建URL对象  POST
            URL postUrl = new URL("https://api.example.com/post");
            HttpURLConnection postConnection = (HttpURLConnection) postUrl.openConnection();

            // 设置请求方法为POST
            postConnection.setRequestMethod("POST");

            // 启用输出流,将参数写入请求体
            postConnection.setDoOutput(true);

            // 拼接参数字符串
            String postData = "param1=" + URLEncoder.encode("value1", StandardCharsets.UTF_8)
                    + "&param2=" + URLEncoder.encode("value2", StandardCharsets.UTF_8);

            // 将参数字符串写入请求体
            postConnection.getOutputStream().write(postData.getBytes(StandardCharsets.UTF_8));

            // 发送请求并获取响应码...

        } catch (IOException e) {
            e.printStackTrace();
        }
    }
}

2.从Java 11开始,推荐使用java.net.http.HttpClient类来进行HTTP通信

import java.io.IOException;
import java.net.URI;
import java.net.URLEncoder;
import java.net.http.HttpClient;
import java.net.http.HttpHeaders;
import java.net.http.HttpRequest;
import java.net.http.HttpResponse;
import java.nio.charset.StandardCharsets;

public class HttpClientExample {
    public static void main(String[] args) {
        try {
            // 创建HttpClient对象
            HttpClient httpClient = HttpClient.newBuilder().build();

            // 创建GET请求,并添加参数到查询字符串中
            String urlString = "https://api.example.com/data?param1=" + URLEncoder.encode("value1", StandardCharsets.UTF_8)
                    + "&param2=" + URLEncoder.encode("value2", StandardCharsets.UTF_8);
            HttpRequest getRequest = HttpRequest.newBuilder()
                    .GET()
                    .uri(URI.create(urlString))
                    .build();

            // 发送GET请求并获取响应
            HttpResponse<String> getResponse = httpClient.send(getRequest, HttpResponse.BodyHandlers.ofString());

            // 处理GET响应...
            System.out.println(getResponse.body());

            // 创建POST请求,并设置请求体
            String postData = "param1=" + URLEncoder.encode("value1", StandardCharsets.UTF_8)
                    + "&param2=" + URLEncoder.encode("value2", StandardCharsets.UTF_8);
            HttpRequest postRequest = HttpRequest.newBuilder()
                    .POST(HttpRequest.BodyPublishers.ofString(postData))
                    .uri(URI.create("https://api.example.com/post"))
                    .header("Content-Type", "application/x-www-form-urlencoded")
                    .build();

            // 发送POST请求并获取响应
            HttpResponse<String> postResponse = httpClient.send(postRequest, HttpResponse.BodyHandlers.ofString());

            // 处理POST响应...
            System.out.println(postResponse.body());
        } catch (IOException | InterruptedException e) {
            e.printStackTrace();
        }
    }
}

3.HttpClient  commons-httpclient包

import com.alibaba.fastjson.JSON;
import org.apache.commons.httpclient.HttpClient;
import org.apache.commons.httpclient.methods.PostMethod;
 
import java.io.IOException;
import java.util.HashMap;
import java.util.Map;
 
public class HttpTest2 {
 
    public static void main(String[] args) {
        HttpClient httpClient = new HttpClient();
        PostMethod postMethod = new PostMethod("http://127.0.0.1/xxx");
 
        postMethod.addRequestHeader("accept", "*/*");
        //设置Content-Type,此处根据实际情况确定
        postMethod.addRequestHeader("Content-Type", "application/x-www-form-urlencoded");
        //必须设置下面这个Header
        //添加请求参数
        Map paraMap = new HashMap();
        paraMap.put("type", "wx");
        paraMap.put("mchid", "10101");
        postMethod.addParameter("consumerAppId", "test");
        postMethod.addParameter("serviceName", "queryMerchantService");
        postMethod.addParameter("params", JSON.toJSONString(paraMap));
        String result = "";
        try {
            int code = httpClient.executeMethod(postMethod);
            if (code == 200){
                result = postMethod.getResponseBodyAsString();
                System.out.println("result:" + result);
            }
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
}

4.Apache HttpClient 中 CloseableHttpClient

import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.NameValuePair;
import org.apache.http.client.entity.UrlEncodedFormEntity;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.client.utils.URIBuilder;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClients;
import org.apache.http.message.BasicNameValuePair;
import org.apache.http.util.EntityUtils;

import java.io.IOException;
import java.net.URI;
import java.net.URISyntaxException;
import java.nio.charset.StandardCharsets;
import java.util.ArrayList;
import java.util.List;

public class ApacheHttpClientExample {
    public static void main(String[] args) {
        try (CloseableHttpClient httpClient = HttpClients.createDefault()) {
            // 创建GET请求,并添加参数到查询字符串中
            URIBuilder uriBuilder = new URIBuilder("https://api.example.com/data");
            uriBuilder.addParameter("param1", "value1");
            uriBuilder.addParameter("param2", "value2");
            HttpGet httpGet = new HttpGet(uriBuilder.build());

            // 发送GET请求并获取响应
            HttpResponse getResponse = httpClient.execute(httpGet);
            HttpEntity getEntity = getResponse.getEntity();
            String getResponseBody = EntityUtils.toString(getEntity, StandardCharsets.UTF_8);

            // 处理GET响应...
            System.out.println(getResponseBody);

            // 创建POST请求,并设置请求体
            HttpPost httpPost = new HttpPost("https://api.example.com/post");
            List<NameValuePair> params = new ArrayList<>();
            params.add(new BasicNameValuePair("param1", "value1"));
            params.add(new BasicNameValuePair("param2", "value2"));
            httpPost.setEntity(new UrlEncodedFormEntity(params, StandardCharsets.UTF_8));

            // 发送POST请求并获取响应
            HttpResponse postResponse = httpClient.execute(httpPost);
            HttpEntity postEntity = postResponse.getEntity();
            String postResponseBody = EntityUtils.toString(postEntity, StandardCharsets.UTF_8);

            // 处理POST响应...
            System.out.println(postResponseBody);
        } catch (IOException | URISyntaxException e) {
            e.printStackTrace();
        }
    }
}

5.RestTemplate 

 @Autowired
 private RestTemplate restTemplate;
 1.
UrlQuery query = new UrlQuery();
 query.add("_w_third_source", "edit");
 query.add("XXX", name == null ? "test" : URLEncoder.encode(name, StandardCharsets.UTF_8));

String url = String.format("/api/xx/v1/xx/%s/link?type=%s&%s", param1, param2, query.build(StandardCharsets.UTF_8));
//query.build — 构建URL查询字符串,即将key-value键值对转换为key1=v1&key2=&key3=v3形式
//签名、请求头
  HttpHeaders headers = new HttpHeaders();
  headers.set("Authorization", authorization);
  headers.set("Content-Type", "application/json");
  headers.set("docs-Date", dateString);
  HttpEntity<?> httpEntity = new HttpEntity<>(headers);
ResponseEntity<XXXResponse> rse=restTemplate.exchange(host + url, HttpMethod.GET, httpEntity, XXXResponse.class).getBody();
if(rse.getStatusCodeValue==200){
//代码  
}

//请求体时 DigestUtils.sha256Hex(content);

2.      //getForObject方法的第二个参数是响应结果的类型
  String url = String.format("https://qyapi.weixin.qq.com/cgi-bin/gettoken? 
  corpid=%s&corpsecret=%s", cropId, secret);
  Map<String, Object> resp = restTemplate.getForObject(url, Map.class);
// Map<String, Object> resp = httpUtil.get(url, Map.class).getBody();
   String accessToken = (String) resp.get("access_token");
   Integer expiresIn = (Integer) resp.get("expires_in");
3. //与2区别  2直接返回响应结果  3 响应结果存储在ResponseEntity对象中
final ResponseEntity<TokenRSP> res = restTemplate.getForEntity(String.format("https://api.weixin.qq.com/cgi-bin/token?grant_type=client_credential&appid=%s&secret=%s", APPID, SECRET), TokenRSP.class);
        final String nowToken = res.getBody().getAccess_token();
        final long expiresTime = res.getBody().getExpires_in();

  • 1
    点赞
  • 6
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
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、付费专栏及课程。

余额充值