写一段java主动发送带json格式参数请求的示例代码
时间: 2023-03-09 15:07:43 浏览: 164
邮件发送和网络请求的java代码
String url = "http://www.example.com/api";
try {
URL obj = new URL(url);
HttpURLConnection con = (HttpURLConnection) obj.openConnection();
con.setRequestMethod("POST");
con.setRequestProperty("Content-Type", "application/json; charset=UTF-8");
JSONObject jsonParam = new JSONObject();
jsonParam.put("param1", "value1");
jsonParam.put("param2", "value2");
// Send post request
con.setDoOutput(true);
DataOutputStream wr = new DataOutputStream(con.getOutputStream());
wr.writeBytes(jsonParam.toString());
wr.flush();
wr.close();
int responseCode = con.getResponseCode();
System.out.println("\nSending 'POST' request to URL : " + url);
System.out.println("Post parameters : " + jsonParam.toString());
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.toString());
} catch (Exception e) {
e.printStackTrace();
}示例代码:
String url = "http://www.example.com/api";
try {
URL obj = new URL(url);
HttpURLConnection con = (HttpURLConnection) obj.openConnection();
con.setRequestMethod("POST");
con.setRequestProperty("Content-Type", "application/json; charset=UTF-8");
JSONObject jsonParam = new JSONObject();
jsonParam.put("参数1", "值1");
jsonParam.put("参数2", "值2");
// 发送post请求
con.setDoOutput(true);
DataOutputStream wr = new DataOutputStream(con.getOutputStream());
wr.writeBytes(jsonParam.toString());
wr.flush();
wr.close();
int responseCode = con.getResponseCode();
System.out.println("\n发送 'POST' 请求到URL : " + url);
System.out.println("参数 : " + jsonParam.toString());
System.out.println("响应码 : " + 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.toString());
} catch (Exception e) {
e.printStackTrace();
}
阅读全文