使用java代码访问对应连接,并发送json格式数据,post请求。
1、首先引用工具类httpclientutil
/*
* 利用httpclient进行post请求的工具类
*/
public class httpclientutil {
public string dopost(string url, map<string, string> headermap, string jsontext, string charset) {
httpclient httpclient = null;
httppost httppost = null;
string result = null;
inputstream in = null;
try {
httpclient = sslclientfactory.createsslclientdefault();
httppost = new httppost(url);
// 设置参数
iterator<entry<string, string>> iterator = headermap.entryset().iterator();
entry<string, string> elem = null;
while (iterator.hasnext()) {
elem = iterator.next();
httppost.addheader(elem.getkey(), elem.getvalue());
}
if (stringutils.isnotblank(jsontext)) {
byte[] bytes = jsontext.getbytes(http.utf_8);
bytearrayentity se = new bytearrayentity(bytes);
httppost.setentity(se);
}
httpresponse response = httpclient.execute(httppost);
if (response != null) {
httpentity resentity = response.getentity();
if (resentity != null) {
in=resentity.getcontent();
result = entityutils.tostring(resentity, charset);
}
}
} catch (exception ex) {
}
finally
{
if (in != null){
try
{
in.close ();
}
catch (ioexception e)
{
e.printstacktrace ();
}
}
}
return result;
}
}2、获取 访问地址、请求头、json格式的请求体
//获取接口地址
string url="http://external.rmcp-zsh.bosafe.com/api/v1/ztexternal/user/change";
//获取请求头
map<string, string> headermap = new hashmap<string, string>();
headermap.put("appid", appid);
headermap.put("randomnumber",s);
headermap.put("timestamp", strtime);
headermap.put("signature", w );
headermap.put("content-type", "application/json");
//获取请求体
jsonobject obj = new jsonobject();
obj.put("appid", appid);
//将待同步对象集合转换为json数据
jsonarray userlist = jsonutil.parsearray(split);
//设置请求体参数
obj.put("userlist",userlist);3、利用工具类httpclientutil 访问 并返回结果
httpclientutil httpclientutil = new httpclientutil();
//发送post请求
string results = httpclientutil.dopost(url, headermap, obj.tojsonstring(), constants.utf8);
//返回结果
jsonobject resultjson = jsonobject.parseobject(results);
string status =resultjson.getstring("status");总结
以上为个人经验,希望能给大家一个参考,也希望大家多多支持代码网。
发表评论