帮我写一个Java方法,传入json和url,将此json发送至这个url
时间: 2024-05-08 14:19:11 浏览: 90
json数据在页面上的传输(java)
4星 · 用户满意度95%
好的,这是一个比较简单的Java方法,可以使用HttpURLConnection来实现:
```
import java.io.OutputStreamWriter;
import java.net.HttpURLConnection;
import java.net.URL;
public void sendJson(String jsonString, String urlStr) throws Exception {
URL url = new URL(urlStr);
HttpURLConnection conn = (HttpURLConnection) url.openConnection();
conn.setRequestMethod("POST");
conn.setRequestProperty("Content-Type", "application/json");
conn.setDoOutput(true);
OutputStreamWriter writer = new OutputStreamWriter(conn.getOutputStream(), "UTF-8");
writer.write(jsonString);
writer.flush();
writer.close();
int responseCode = conn.getResponseCode();
System.out.println("Response Code : " + responseCode);
conn.disconnect();
}
```
你只需要传入json字符串和目标url地址即可。
阅读全文