java给对方接口传输json数据工具类
时间: 2023-08-13 21:03:27 浏览: 157
以下是一个使用 Java 的工具类,用于向对方接口传输 JSON 数据的示例:
```java
import java.io.BufferedReader;
import java.io.InputStreamReader;
import java.io.OutputStream;
import java.net.HttpURLConnection;
import java.net.URL;
public class HttpJsonUtils {
public static String sendPostRequest(String url, String jsonInputString) {
try {
// 创建连接
HttpURLConnection connection = (HttpURLConnection) new URL(url).openConnection();
connection.setRequestMethod("POST");
connection.setRequestProperty("Content-Type", "application/json");
connection.setDoOutput(true);
// 发送请求
try (OutputStream outputStream = connection.getOutputStream()) {
byte[] input = jsonInputString.getBytes("utf-8");
outputStream.write(input, 0, input.length);
}
// 获取响应
BufferedReader reader = new BufferedReader(new InputStreamReader(connection.getInputStream()));
StringBuilder response = new StringBuilder();
String line;
while ((line = reader.readLine()) != null) {
response.append(line);
}
reader.close();
// 关闭连接
connection.disconnect();
return response.toString();
} catch (Exception e) {
e.printStackTrace();
}
return null;
}
}
```
您可以使用上述工具类来发送 HTTP POST 请求并传输 JSON 数据。使用示例代码如下:
```java
public class Main {
public static void main(String[] args) {
String url = "http://example.com/api/endpoint";
String jsonInputString = "{\"name\":\"John\", \"age\":30, \"city\":\"New York\"}";
String response = HttpJsonUtils.sendPostRequest(url, jsonInputString);
System.out.println(response);
}
}
```
确保将 `url` 替换为目标接口的实际 URL,
阅读全文