http接口的调用之json入参及map入参

1.按照文档先写入参数,这里主要介绍

Json格式的String字符串,包括拼接数组

String sqr_arry [] = new String[rowList.size()];
for(int i = 0; i < rowList.size(); i++) {
FieldList field_p = rowList.get(i);//查询每个家庭成员的姓名和身份证
String xm = field_p.get("pxm");
String sfzh = field_p.get("pzjhm");
String sq = "{\"xm\":\""+xm+"\",\"sfzh\":\""+sfzh+"\"}";
sqr_arry [i] = sq;//把各个家庭对象放进数组
}
String sqrs = "";
for(int i = 0;i < rowList.size(); i++ ){
sqrs += sqr_arry [i]+",";//从数组中取对象并做拼接
}
int idx = sqrs.lastIndexOf(",");//去掉最后一个逗号
sqrs = sqrs.substring(0,idx);

String sqr = "["+sqrs+"]";
String pararsa="{\"jkbm\":\"11\",\"batchid\":\""+ID+"\",\"sqrs\":"+sqr+",\"remark\":\""+cxyy+"\"}";//sqr为数组,解析完外层必须不带双引号“”;

String urlPost = "http://IP地址:端口号/***/***/***.action"; //接口地址

String resValue = HttpPost(urlPost, pararsa);//请求接口

 

/**
* 模拟HttpPost请求
* @param url
* @param jsonString
* @return
*/
public static String HttpPost(String url, String jsonString){
CloseableHttpResponse response = null;
CloseableHttpClient httpClient = HttpClientBuilder.create().build();//创建CloseableHttpClient
HttpPost httpPost = new HttpPost(url);//实现HttpPost
RequestConfig requestConfig = RequestConfig.custom().setSocketTimeout(3000).setConnectTimeout(3000).build();
httpPost.setConfig(requestConfig); //设置httpPost的状态参数
httpPost.addHeader("Content-Type", "application/json");//设置httpPost的请求头中的MIME类型为json
StringEntity requestEntity = new StringEntity(jsonString, "utf-8");
httpPost.setEntity(requestEntity);//设置请求体
try {
response = httpClient.execute(httpPost, new BasicHttpContext());//执行请求返回结果
if (response.getStatusLine().getStatusCode() != HttpStatus.SC_OK) {
return null;
}
HttpEntity entity = response.getEntity();
if (entity != null) {
String resultStr = EntityUtils.toString(entity, "utf-8");
return resultStr;
} else {
return null;
}
} catch (Exception e) {
logger.error("httpPost method exception handle-- > " + e);
return null;
} finally {
if (response != null){
try {
response.close();//最后关闭response
} catch (IOException e) {
logger.error("httpPost method IOException handle -- > " + e);
}
}if(httpClient != null){try {httpClient.close();} catch (IOException e) {logger.error("httpPost method exception handle-- > " + e);}}}}

 

/**
* 模拟HttpGet 请求
* @param url
* @return
*/
public static String HttpGet(String url){
//单位毫秒
RequestConfig requestConfig = RequestConfig.custom()
.setConnectionRequestTimeout(3000).setConnectTimeout(3000)
.setSocketTimeout(3000).build();//设置请求的状态参数

CloseableHttpClient httpclient = HttpClients.createDefault();//创建 CloseableHttpClient
HttpGet httpGet = new HttpGet(url);
httpGet.setConfig(requestConfig);

CloseableHttpResponse response = null;
try {
response = httpclient.execute(httpGet);//返回请求执行结果
int statusCode = response.getStatusLine().getStatusCode();//获取返回的状态值
if (statusCode != HttpStatus.SC_OK) {
return null;
} else {
String result = EntityUtils.toString(response.getEntity(), "UTF-8");
return result;
}
} catch (Exception e) {
logger.error("httpget Exception handle-- > " + e);
} finally {
if (response != null){
try {
response.close();//关闭response
} catch (IOException e) {
logger.error("httpget IOException handle-- > " + e);
}
}
if(httpclient != null){
try {
httpclient.close();//关闭httpclient
} catch (IOException e) {
logger.error("httpget IOException handle-- > " + e);
}
}
}
return null;
}

工具类HttpUtils  入参为map

package sr.shjz_zt2.util;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.PrintWriter;
import java.util.List;
import java.util.Map;

import net.sf.json.JSONArray;

/**
* 用于模拟HTTP请求中GET/POST方式
*
* @author
*
*/
public class HttpUtils {


/**
* 发送GET请求
*
* @param url
* 目的地址
* @param parameters
* 请求参数,Map类型。
* @return 远程响应结果
*/
public static JSONArray sendGet(String url, Map<String, String> parameters) {
String result = "";
BufferedReader in = null;// 读取响应输入流
StringBuffer sb = new StringBuffer();// 存储参数
String params = "";// 编码之后的参数
String full_url = "";
try {
// 编码请求参数
if (parameters.size() == 0) {
full_url = url;
} else if (parameters.size() == 1) {
for (String name : parameters.keySet()) {
sb.append(name)
.append("=")
.append(java.net.URLEncoder.encode(
parameters.get(name), "UTF-8"));
}
params = sb.toString();
full_url = url + "?" + params;
} else {
for (String name : parameters.keySet()) {
sb.append(name)
.append("=")
.append(java.net.URLEncoder.encode(
parameters.get(name), "UTF-8")).append("&");
}
String temp_params = sb.toString();
params = temp_params.substring(0, temp_params.length() - 1);
full_url = url + "?" + params;
}

System.out.println(full_url);
// 创建URL对象
java.net.URL connURL = new java.net.URL(full_url);
// 打开URL连接
java.net.HttpURLConnection httpConn = (java.net.HttpURLConnection) connURL
.openConnection();
// 设置通用属性
httpConn.setRequestProperty("Accept", "*/*");
httpConn.setRequestProperty("Connection", "Keep-Alive");
httpConn.setRequestProperty("User-Agent",
"Mozilla/4.0 (compatible; MSIE 8.0; Windows NT 6.1)");
// 建立实际的连接
httpConn.connect();
// 响应头部获取
Map<String, List<String>> headers = httpConn.getHeaderFields();
// 遍历所有的响应头字段
for (String key : headers.keySet()) {
System.out.println(key + "\t:\t" + headers.get(key));
}
// 定义BufferedReader输入流来读取URL的响应,并设置编码方式
in = new BufferedReader(new InputStreamReader(
httpConn.getInputStream(), "UTF-8"));
String line;
// 读取返回的内容
while ((line = in.readLine()) != null) {
result += line;
}
} catch (Exception e) {
e.printStackTrace();
} finally {
try {
if (in != null) {
in.close();
}
} catch (IOException ex) {
ex.printStackTrace();
}
}
return JSONArray.fromObject(result);
}

/**
* 发送POST请求
*
* @param url
* 目的地址
* @param parameters
* 请求参数,Map类型。
* @return 远程响应结果
*/
public static String sendPost(String url, Map<String, String> parameters) {
String result = "";// 返回的结果
BufferedReader in = null;// 读取响应输入流
PrintWriter out = null;
StringBuffer sb = new StringBuffer();// 处理请求参数
String params = "";// 编码之后的参数
try {
// 编码请求参数
if (parameters.size() == 1) {
for (String name : parameters.keySet()) {
sb.append(name)
.append("=")
.append(java.net.URLEncoder.encode(
parameters.get(name), "UTF-8"));
}
params = sb.toString();
} else {
for (String name : parameters.keySet()) {
sb.append(name)
.append("=")
.append(java.net.URLEncoder.encode(
parameters.get(name), "UTF-8")).append("&");
}
String temp_params = sb.toString();
params = temp_params.substring(0, temp_params.length() - 1);
}
// 创建URL对象
java.net.URL connURL = new java.net.URL(url);
// 打开URL连接
java.net.HttpURLConnection httpConn = (java.net.HttpURLConnection) connURL
.openConnection();
// 设置通用属性
httpConn.setRequestProperty("Accept", "*/*");
httpConn.setRequestProperty("Connection", "Keep-Alive");
httpConn.setRequestProperty("content-type", "application/x-www-form-urlencoded");
httpConn.setRequestProperty("User-Agent",
"Mozilla/4.0 (compatible; MSIE 8.0; Windows NT 6.1)");
// 设置POST方式
httpConn.setDoInput(true);
httpConn.setDoOutput(true);
// 获取HttpURLConnection对象对应的输出流
out = new PrintWriter(httpConn.getOutputStream());
// 发送请求参数
out.write(params);
// flush输出流的缓冲
out.flush();
// 定义BufferedReader输入流来读取URL的响应,设置编码方式
in = new BufferedReader(new InputStreamReader(
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();
}
}
return result;
}

public static String ascii2native(String asciicode) {
String[] asciis = asciicode.split("\\\\u");
String nativeValue = asciis[0];
try {
for (int i = 1; i < asciis.length; i++) {
String code = asciis[i];
nativeValue += (char) Integer
.parseInt(code.substring(0, 4), 16);
if (code.length() > 4) {
nativeValue += code.substring(4, code.length());
}
}
} catch (NumberFormatException e) {
return asciicode;
}
return nativeValue;
}


}

调用示例

public String execute(ServiceData sdata) {
String msg = "";
try {
log.info("进入GetGaxxManager");
String ubody = sdata.getRequestParam().getString("ubody");
log.info("ubody=="+ubody);

JSONObject json = JSONObject.parseObject(ubody);
String xm = json.getString("xm");
String sfz = json.getString("sfz");

//post方式接口传递路径
String urlPost = ""; //接口地址
Map<String,String> map_grxx = new HashMap();
String sfzh = sfz;
xm = xm;
String seriaNo = "202010301000000000";
map_grxx.put("sfzh", sfzh);
map_grxx.put("xm", xm);
map_grxx.put("seriaNo", seriaNo);
System.out.println("请求参数为=============="+map_grxx);
String resValue = HttpUtils.sendPost(urlPost, map_grxx);
System.out.println("返回参数为=============="+resValue);
JSONObject json_family = JSONObject.parseObject(resValue);
log.info("公安返回信息="+json_family);
String res_msg = json_family.getString("msg");
String string_struct = json_family.getString("struct");
JSONObject json_struct = JSONObject.parseObject(string_struct);
String data_person_string = json_struct.getString("data");
JSONArray data_person_jsonArray = JSONArray.parseArray(data_person_string);
List<JSONObject> jsonObjects = new ArrayList<JSONObject>();
Map map = new HashMap();
if (data_person_jsonArray.size()>0) {
for(int i = 0 ; i<data_person_jsonArray.size();i++){
JSONObject json_family_hc = JSONObject.parseObject(data_person_jsonArray.get(i).toString());
String cyxm = json_family_hc.getString("xm");//姓名
String cysfz = json_family_hc.getString("sfzh");//姓名
log.info("身份证=="+cysfz+";姓名=="+cyxm);
JSONObject jsonObject = new JSONObject();
jsonObject.put("xm", cyxm);
jsonObject.put("sfz",cysfz);
jsonObjects.add(jsonObject);
map.put(i, cysfz);
msg = "{\"success\" : true,\"errorCode\" : \"200\", \"errorMsg\" : \"公安信息查询完成\", \"data\" :" +jsonObjects + "}";
}
}
//婚姻得接口
HyWsManager hyWsManager = new HyWsManager();
for (Object key : map.keySet()) {
String dsfz = map.get(key).toString().replace("\"", "");

JsonObject json_hy = null;

try{
json_hy = hyWsManager.getHyhjxx(dsfz,"1");//通过婚姻接口完善户籍信息
}catch(Exception e){
log.info(e);
continue;
}

if("{}".equals(json_hy.toString()) || map.containsValue(json_hy.get("dsfz").toString().replace("\"", "")) ){
continue;
}else{
JSONObject jsonObject = new JSONObject();
jsonObject.put("xm", json_hy.get("dxm").toString().replace("\"", ""));
jsonObject.put("sfz",json_hy.get("dsfz").toString().replace("\"", ""));
jsonObjects.add(jsonObject);
msg = "{\"success\" : true,\"errorCode\" : \"200\", \"errorMsg\" : \"公安信息查询完成\", \"data\" :" +jsonObjects + "}";
log.info("msg======"+msg);
}
}
return msg;
} catch (Exception e) {
msg = "{\"success\" : false,\"errorCode\" : \"500\", \"errorMsg\" : \"公安信息接口异常" + e + "\"}";
return msg;
}
}

 

posted @   武魂95级蓝银草  阅读(3986)  评论(0编辑  收藏  举报
努力加载评论中...
点击右上角即可分享
微信分享提示