请求http://192.168.10.123:41002/wechatpay/payment?amt=1000&branchId=1000000002&ccy=CNY的java多种方式
时间: 2024-12-23 11:19:38 浏览: 8
请求一个HTTP服务通常涉及网络编程,尤其是在Java中,可以使用多种库来发送这样的GET请求,例如`HttpURLConnection`, `Apache HttpClient`, 或者第三方库如`OkHttp`或`Spring WebClient`等。以下是几种常见的方法:
1. 使用HttpURLConnection:
```java
URL url = new URL("http://192.168.10.123:41002/wechatpay/payment");
HttpURLConnection connection = (HttpURLConnection) url.openConnection();
connection.setRequestMethod("GET");
connection.addParameter("amt", "1000");
connection.addParameter("branchId", "1000000002");
connection.addParameter("ccy", "CNY"); // 这里假设addParameter方法存在
try {
int responseCode = connection.getResponseCode();
BufferedReader in = new BufferedReader(new InputStreamReader(connection.getInputStream()));
String inputLine;
StringBuffer content = new StringBuffer();
while ((inputLine = in.readLine()) != null) {
content.append(inputLine);
}
in.close();
System.out.println(content.toString());
} finally {
connection.disconnect();
}
```
2. Apache HttpClient示例:
```java
CloseableHttpClient httpClient = HttpClients.createDefault();
HttpGet httpGet = new HttpGet(url.toURI());
NameValuePair[] params = {new NameValuePair("amt", "1000"), ...}; // 类似上面添加参数
httpGet.setParameters(params); // 添加参数到请求头
CloseableHttpResponse response = httpClient.execute(httpGet);
try {
EntityUtils.consume(response.getEntity());
System.out.println(response.getStatusLine().getStatusCode());
} finally {
response.close();
httpClient.close();
}
```
3. Spring WebClient示例(如果项目依赖了Spring Boot):
```java
RestTemplate restTemplate = new RestTemplate();
String urlWithParams = "/wechatpay/payment?amt=1000&branchId=1000000002&ccy=CNY";
MultiValueMap<String, Object> headers = new LinkedMultiValueMap<>();
headers.add("Content-Type", MediaType.APPLICATION_FORM_URLENCODED_VALUE);
ResponseEntity<String> response = restTemplate.exchange(urlWithParams, HttpMethod.GET, EntityUtils.createHttpEntity(headers), String.class);
System.out.println(response.getBody());
```
阅读全文