遠程調用API接口 (Post請求和Json格式請求)以及參數處理

package com.xjgzinfo.zhwwpt.sdk.core.httpClient;

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;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import com.google.gson.JsonObject;

public class ZwXjHttpRequestUtil {

private static final Logger logger = LoggerFactory.getLogger(ZwXjHttpRequestUtil.class);
    
    private static final String UTF8 = "UTF-8";
    private static final String CONTENT_TYPE_FORM = "application/x-www-form-urlencoded";
    
    public static final String POST_REQUEST = "POST";
    private static final String CONTENT_TYPE_JSON = "application/json";
    /**
     * POST 模式提交
     * @param url 請求URL 地址
     * @param param 請求參數form表單
     * @return
     */
    public static String doPostForm(String url, String accessToken, String param){
        String result = "";
        HttpResponse response = null;
        HttpPost httpost = new HttpPost(url);
        httpost.setHeader("Authorization", "Bearer "+accessToken);
        CloseableHttpClient httpclient = HttpClients.custom().build();
        try {
            //解決中文亂碼問題  
            StringEntity entity = new StringEntity(param, UTF8);
            entity.setContentEncoding(UTF8);
            entity.setContentType(CONTENT_TYPE_FORM);
            httpost.setEntity(entity);
            
            response = httpclient.execute(httpost);
            result = EntityUtils.toString(response.getEntity());
            
        } catch (Exception e) {                      
            logger.error("調用接口發生異常,"+e);
        } finally {
            try {
                EntityUtils.consume(response.getEntity());
            } catch (Exception e) {
                logger.error("調用接口組裝result異常,"+e);
            }
            httpost.abort();
        }
        return result;
    }
    
    /**
     * POST 模式提交
     * @param url 請求URL 地址
     * @param param 請求參數json
     * @return
     */
    public static String doPostFormToJson(String url, String accessToken, String param){
        String result = "";
        HttpResponse response = null;
        HttpPost httpost = new HttpPost(url);
        httpost.setHeader("Authorization", "Bearer "+accessToken);
        CloseableHttpClient httpclient = HttpClients.custom().build();
        try {
            //解決中文亂碼問題  
            StringEntity entity = new StringEntity(param);
            entity.setContentEncoding(UTF8);
            entity.setContentType(CONTENT_TYPE_JSON);
            httpost.setEntity(entity);
            
            response = httpclient.execute(httpost);
            result = EntityUtils.toString(response.getEntity());
            
        } catch (Exception e) {                      
            logger.error("調用接口發生異常,"+e);
        } finally {
            try {
                EntityUtils.consume(response.getEntity());
            } catch (Exception e) {
                logger.error("調用接口組裝result異常,"+e);
            }
            httpost.abort();
        }
        return result;
    }
    
}

調用部分:

public Map<String, Object> yldzxxcx(String sfz) {
		//返回結果
		Map<String,Object>resultMap=new HashMap<String, Object>();
		//響應狀態
		Map<String,Object>status=new HashMap<String, Object>();
		status.put("code", 200);
		status.put("text", "成功");
		Custom<List<BaoXianMessageDto>>custom=new Custom<>();

		try {
			//獲取accesstoken
			Map<String,String> wxGzhATMap = jmAppUserDao.selectAccessTokenByName("zwptInter");
			String accessToken=wxGzhATMap.get("ACCESSTOKEN");
			ZwXjHttpRequestUtil  zwxjHttpRequestUtil=new ZwXjHttpRequestUtil();
			String url="XXXXXXXXXXXXXXXXXXXXX";
			//封裝請求參數
			String param="Params="+sfz;
			String resultString=zwxjHttpRequestUtil.doPostForm(url, accessToken, param);	
			JSONObject jsonObject=JSON.parseObject(resultString);
			
			//0失敗 1成功
			Integer flag=jsonObject.getJSONObject("custom").getInteger("code");
			if(flag==1 && flag.equals(1)) {
						
				String returncount=jsonObject.getJSONObject("custom").getString("returncount");
						
				
				String str=jsonObject.getJSONObject("custom").getString("result");
				ArrayList<BaoXianMessageDto> userList  = 
						JSON.parseObject(str, new TypeReference<ArrayList<BaoXianMessageDto>>(){});
				
				String recordcount=jsonObject.getJSONObject("custom").getString("recordcount");		
				String text=jsonObject.getJSONObject("custom").getString("text");
				
				custom.setReturncount(returncount);
				custom.setRecordcount(recordcount);
				custom.setResult(userList);
				custom.setCode("1");
				custom.setText(text);
				
				//封裝返回結果
				resultMap.put("custom", custom);
				
				resultMap.put("status", status);
			}else {
				custom.setCode("0");
				custom.setText("未查詢到結果信息,請確認輸入的信息是否正確!");
				resultMap.put("custom", custom);
				resultMap.put("status", status);
			}
		} catch (Exception e) {

				resultMap.put("custom", null);
				status.put("code", 400);
				status.put("text", "失敗");
				resultMap.put("status", status);
		}
				
				return resultMap;
	}

 

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章