这是一个Get的请求http://cwb.cn/flow-config/getByUuid?uuid=cb7722054a164e6db055da0e017cf311其中Headers中要传一个accessToken的参数然后,uuid需要动态的传参请用Java代码来实现
时间: 2024-10-19 16:07:09 浏览: 11
femug-cwb.github.io:FEMUG-CWB网站的源代码-git source code
在Java中,你可以使用`HttpURLConnection`或者第三方库如`Apache HttpClient`或`OkHttp`来发送GET请求,并传递动态参数。这里我将以`HttpURLConnection`为例来展示代码,因为它是Java标准库的一部分,无需额外安装。
首先,你需要导入必要的库:
```java
import java.io.BufferedReader;
import java.io.InputStreamReader;
import java.net.HttpURLConnection;
import java.net.URL;
import java.nio.charset.StandardCharsets;
```
然后,创建一个方法来构建并发送GET请求:
```java
public String sendGetRequest(String accessToken, String uuid) {
try {
URL url = new URL("http://cwb.cn/flow-config/getByUuid");
HttpURLConnection connection = (HttpURLConnection) url.openConnection();
// 设置请求方法为GET
connection.setRequestMethod("GET");
// 添加请求头,包括授权令牌
connection.setRequestProperty("Authorization", "Bearer " + accessToken);
connection.setRequestProperty("Content-Type", "application/x-www-form-urlencoded; charset=UTF-8"); // 根据实际需求设置
// 动态添加查询参数
StringBuilder queryBuilder = new StringBuilder("uuid=");
queryBuilder.append(uuid);
connection.setRequestProperty("QUERY_STRING", queryBuilder.toString());
// 打开连接并获取响应码
connection.connect();
if (connection.getResponseCode() == HttpURLConnection.HTTP_OK) {
BufferedReader reader = new BufferedReader(new InputStreamReader(connection.getInputStream(), StandardCharsets.UTF_8));
StringBuilder response = new StringBuilder();
String line;
while ((line = reader.readLine()) != null) {
response.append(line);
}
reader.close();
return response.toString();
} else {
throw new RuntimeException("Failed to retrieve data. Response code: " + connection.getResponseCode());
}
} catch (Exception e) {
throw new RuntimeException("Error sending GET request: ", e);
}
}
```
你可以这样调用这个方法:
```java
String accessToken = "your_access_token";
String uuid = "cb7722054a164e6db055da0e017cf311";
String jsonResponse = sendGetRequest(accessToken, uuid);
```
注意替换`"your_access_token"`为你真实的授权令牌。同时,如果服务器对请求参数有特定的要求,比如URL编码,你可能需要进一步处理`uuid`参数。
阅读全文