java post json请求_java模拟post请求发送json

java模拟post请求发送json,用两种方式实现,第一种是HttpURLConnection发送post请求,第二种是使用httpclient模拟post请求。

方法一:

public staticString sendPost(String url_param, String param) {

String result= "";//返回的结果

BufferedReader in = null;//读取响应输入流//PrintWriter out = null;

try{//创建URL对象

URL url = newURL(url_param);//打开URL连接

java.net.HttpURLConnection httpConn =(java.net.HttpURLConnection) url

.openConnection();//设置属性

httpConn.setRequestProperty("Content-Type","application/json");//设置POST方式

httpConn.setDoInput(true);

httpConn.setDoOutput(true);

httpConn.setRequestMethod("POST");

httpConn.setUseCaches(false);

httpConn.setInstanceFollowRedirects(true);//获取HttpURLConnection对象对应的输出流

DataOutputStream out = newDataOutputStream(httpConn.getOutputStream());

out.write(param.getBytes("utf-8"));//flush输出流的缓冲

out.flush();

out.close();//定义BufferedReader输入流来读取URL的响应,设置编码方式

in = new BufferedReader(newInputStreamReader(httpConn

.getInputStream(),"UTF-8"));

String line;//读取返回的内容

while ((line = in.readLine()) != null) {

result+=line;

}

}catch(Exception e) {

e.printStackTrace();

}finally{try{/*if (out != null) {

out.close();

}*/

if (in != null) {

in.close();

}

}catch(IOException ex) {

ex.printStackTrace();

}

}returnresult;

}

方法二:

public String sendPost(String url, String data) {

String response = null;

log.info("url: " + url);

log.info("request: " + data);

try {

CloseableHttpClient httpclient = null;

CloseableHttpResponse httpresponse = null;

try {

httpclient = HttpClients.createDefault();

HttpPost httppost = new HttpPost(url);

StringEntity stringentity = new StringEntity(data,

ContentType.create("text/json", "UTF-8"));

httppost.setEntity(stringentity);

httpresponse = httpclient.execute(httppost);

response = EntityUtils

.toString(httpresponse.getEntity());

log.info("response: " + response);

} finally {

if (httpclient != null) {

httpclient.close();

}

if (httpresponse != null) {

httpresponse.close();

}

}

} catch (Exception e) {

e.printStackTrace();

}

return response;

}

  • 0
    点赞
  • 4
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值