写一个java方法,访问公网ip端口传递json
时间: 2023-05-27 13:07:45 浏览: 224
以下是一个示例Java方法,使用HttpURLConnection类发送JSON数据到公共IP地址和端口:
```java
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.OutputStream;
import java.net.HttpURLConnection;
import java.net.URL;
public class JsonSender {
public static void sendJson(String ip, int port, String json) throws IOException {
String url = "http://" + ip + ":" + port;
URL obj = new URL(url);
HttpURLConnection con = (HttpURLConnection) obj.openConnection();
// 设置请求方法为POST
con.setRequestMethod("POST");
// 设置请求头
con.setRequestProperty("Content-Type", "application/json");
// 启用输出流
con.setDoOutput(true);
// 获取输出流并写入JSON数据
OutputStream os = con.getOutputStream();
os.write(json.getBytes("UTF-8"));
os.flush();
os.close();
// 获取响应结果
int responseCode = con.getResponseCode();
System.out.println("Response Code: " + responseCode);
// 读取响应结果
BufferedReader in = new BufferedReader(new InputStreamReader(con.getInputStream()));
String inputLine;
StringBuffer response = new StringBuffer();
while ((inputLine = in.readLine()) != null) {
response.append(inputLine);
}
in.close();
// 输出响应结果
System.out.println("Response Body: " + response.toString());
}
public static void main(String[] args) throws IOException {
String ip = "your.public.ip.address";
int port = 8080;
String json = "{\"name\":\"John\",\"age\":30,\"city\":\"New York\"}";
sendJson(ip, port, json);
}
}
```
在使用该方法时,需要将`your.public.ip.address`替换为实际的公共IP地址,`8080`替换为实际的端口号,以及`{\"name\":\"John\",\"age\":30,\"city\":\"New York\"}`替换为实际的JSON数据。
阅读全文