java get请求传json数据 比如传一个long类型的id
时间: 2023-11-21 08:05:16 浏览: 103
可以使用以下代码实现:
```java
import java.io.BufferedReader;
import java.io.InputStreamReader;
import java.net.HttpURLConnection;
import java.net.URL;
import java.util.HashMap;
import java.util.Map;
public class Main {
public static void main(String[] args) {
try {
// 设置请求参数
long id = 123456L;
Map<String, Object> params = new HashMap<>();
params.put("id", id);
// 拼接请求url
StringBuilder sb = new StringBuilder("http://example.com/api/getData");
sb.append("?").append(buildParams(params));
// 发送请求
URL url = new URL(sb.toString());
HttpURLConnection connection = (HttpURLConnection) url.openConnection();
connection.setRequestMethod("GET");
// 读取响应内容
BufferedReader reader = new BufferedReader(new InputStreamReader(connection.getInputStream()));
StringBuilder response = new StringBuilder();
String line;
while ((line = reader.readLine()) != null) {
response.append(line);
}
reader.close();
System.out.println(response.toString());
} catch (Exception e) {
e.printStackTrace();
}
}
// 将请求参数转换为url参数格式
private static String buildParams(Map<String, Object> params) {
if (params == null || params.isEmpty()) {
return "";
}
StringBuilder sb = new StringBuilder();
for (Map.Entry<String, Object> entry : params.entrySet()) {
if (sb.length() > 0) {
sb.append("&");
}
sb.append(entry.getKey()).append("=").append(entry.getValue());
}
return sb.toString();
}
}
```
以上代码将会发送一个GET请求到`http://example.com/api/getData?id=123456`,其中id的值为123456。你可以根据自己的需要修改请求url和参数。
阅读全文