天天看點

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 {

} 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 請求

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);

response = httpclient.execute(httpGet);//傳回請求執行結果

int statusCode = response.getStatusLine().getStatusCode();//擷取傳回的狀态值

if (statusCode != HttpStatus.SC_OK) {

String result = EntityUtils.toString(response.getEntity(), "UTF-8");

return result;

logger.error("httpget Exception handle-- > " + e);

response.close();//關閉response

logger.error("httpget IOException handle-- > " + e);

if(httpclient != null){

httpclient.close();//關閉httpclient

}

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 {

parameters.get(name), "UTF-8")).append("&");

String temp_params = sb.toString();

params = temp_params.substring(0, temp_params.length() - 1);

}

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請求

public static String sendPost(String url, Map<String, String> parameters) {

String result = "";// 傳回的結果

PrintWriter out = null;

StringBuffer sb = new StringBuffer();// 處理請求參數

if (parameters.size() == 1) {

java.net.URL connURL = new java.net.URL(url);

httpConn.setRequestProperty("content-type", "application/x-www-form-urlencoded");

// 設定POST方式

httpConn.setDoInput(true);

httpConn.setDoOutput(true);

// 擷取HttpURLConnection對象對應的輸出流

out = new PrintWriter(httpConn.getOutputStream());

// 發送請求參數

out.write(params);

// flush輸出流的緩沖

out.flush();

// 定義BufferedReader輸入流來讀取URL的響應,設定編碼方式

if (out != null) {

out.close();

return result;

public static String ascii2native(String asciicode) {

String[] asciis = asciicode.split("\\\\u");

String nativeValue = asciis[0];

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("\"", "")) ){

}else{

jsonObject.put("xm", json_hy.get("dxm").toString().replace("\"", ""));

jsonObject.put("sfz",json_hy.get("dsfz").toString().replace("\"", ""));

msg = "{\"success\" : true,\"errorCode\" : \"200\", \"errorMsg\" : \"公安資訊查詢完成\", \"data\" :" +jsonObjects + "}";

log.info("msg======"+msg);

return msg;

} catch (Exception e) {

msg = "{\"success\" : false,\"errorCode\" : \"500\", \"errorMsg\" : \"公安資訊接口異常" + e + "\"}";