远程调用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;
	}

 

  • 1
    点赞
  • 7
    收藏
    觉得还不错? 一键收藏
  • 3
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 3
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值