使用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");