100字范文,内容丰富有趣,生活中的好帮手!
100字范文 > java发送http post请求报文_Java 用HTTP的方式发送JSON报文请求

java发送http post请求报文_Java 用HTTP的方式发送JSON报文请求

时间:2018-07-07 09:57:00

相关推荐

java发送http post请求报文_Java 用HTTP的方式发送JSON报文请求

String resp= null;

JSONObject obj= newJSONObject();

obj.put("name", "张三");

obj.put("age", "18");

String query=obj.toString();

log.info("发送到URL的报文为:");

log.info(query);try{

URL url= new URL("http://127.0.0.1:8888"); //url地址

HttpURLConnection connection=(HttpURLConnection) url.openConnection();

connection.setDoInput(true);

connection.setDoOutput(true);

connection.setRequestMethod("POST");

connection.setUseCaches(false);

connection.setInstanceFollowRedirects(true);

connection.setRequestProperty("Content-Type","application/json");

connection.connect();try (OutputStream os =connection.getOutputStream()) {

os.write(query.getBytes("UTF-8"));

}try (BufferedReader reader = newBufferedReader(newInputStreamReader(connection.getInputStream()))) {

String lines;

StringBuffer sbf= newStringBuffer();while ((lines = reader.readLine()) != null) {

lines= new String(lines.getBytes(), "utf-8");

sbf.append(lines);

}

log.info("返回来的报文:"+sbf.toString());

resp=sbf.toString();

}

connection.disconnect();

}catch(Exception e) {

e.printStackTrace();

}finally{

JSONObject json=(JSONObject)JSON.parse(resp);

}

本内容不代表本网观点和政治立场,如有侵犯你的权益请联系我们处理。
网友评论
网友评论仅供其表达个人看法,并不表明网站立场。