java发送post请求传json数据

java发送post请求传json数据,第1张

java发送post请求传json数据
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import org.apache.http.HttpResponse;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.entity.StringEntity;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClients;
import org.apache.http.util.EntityUtils;




//定义发送数据
JSonObject param = new JSonObject();
param.put("username", "zhangshan");
param.put("age", "18");
//定义接收数据
JSonObject result = new JSonObject();

String url = "http://www.baidu.com";
HttpPost httpPost = new HttpPost(url);
CloseableHttpClient client = HttpClients.createDefault();
//请求参数转JOSN字符串
StringEntity entity = new StringEntity(param.toString(), "UTF-8");
entity.setContentEncoding("UTF-8");
entity.setContentType("application/json");
httpPost.setEntity(entity);
try {
	HttpResponse response = client.execute(httpPost);
	if (response.getStatusLine().getStatusCode() == 200) {
		result = JSON.parseObject(EntityUtils.toString(response.getEntity()));
	}
} catch (IOException e) {
	e.printStackTrace();
	result.put("error", "连接错误!");
}

欢迎分享,转载请注明来源:内存溢出

原文地址: http://outofmemory.cn/zaji/5637689.html

(0)
打赏 微信扫一扫 微信扫一扫 支付宝扫一扫 支付宝扫一扫
上一篇 2022-12-16
下一篇 2022-12-16

发表评论

登录后才能评论

评论列表(0条)

保存