HttpPost接口调用

package com.fastech.test;

import java.io.IOException;
import java.io.UnsupportedEncodingException;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import org.apache.http.HttpEntity;
import org.apache.http.NameValuePair;
import org.apache.http.client.ClientProtocolException;
import org.apache.http.client.entity.UrlEncodedFormEntity;
import org.apache.http.client.methods.CloseableHttpResponse;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClients;
import org.apache.http.message.BasicNameValuePair;
import org.apache.http.util.EntityUtils;

import net.sf.json.JSONArray;
import net.sf.json.JSONObject;

public class HttpPostTool {
/**
 * 需要导入 json-lib-2.4-jdk15.jar
 *       httpclient-4.3.1.jar
 *       httpcore-4.3.jar
 * @param parammap 传参
 * @param postpath 接口路径
 * @author mnn
 * @return JSONObject 调用接口返回数据
 * */
    public JSONObject httpPostTool(Map parammap,String postpath) {
        JSONObject jsonobject=null;
        CloseableHttpClient httpclient = HttpClients.createDefault();
        // 创建httppost
        HttpPost httppost = new HttpPost(postpath);
        // 创建参数队列
        List formparams = new ArrayList();
        for (Map.Entry entry : parammap.entrySet()) { 
            formparams.add(new BasicNameValuePair(entry.getKey(), entry.getValue().toString()));
        }
        
        UrlEncodedFormEntity uefEntity;
        try {
            uefEntity = new UrlEncodedFormEntity(formparams, "UTF-8");
            httppost.setEntity(uefEntity);
            CloseableHttpResponse response = httpclient.execute(httppost);
            try {
                HttpEntity entity = response.getEntity();
                if (entity != null) {
                    // 调用接口返回的字符串
                    String responseString = EntityUtils.toString(entity, "UTF-8");
                    jsonobject = JSONObject.fromObject(responseString);
                }
            } finally {
                response.close();
            }
        } catch (ClientProtocolException e) {
            e.printStackTrace();
        } catch (UnsupportedEncodingException e1) {
            e1.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            // 关闭连接,释放资源
            try {
                httpclient.close();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
         return jsonobject;
    }
}

你可能感兴趣的:(接口)