httpclient模拟post,get请求

发送json封装的表单数据。

发送请求的工具类:

package com.chinecredit.eccis.utils;

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

import org.apache.http.HttpEntity;
import org.apache.http.HttpStatus;
import org.apache.http.NameValuePair;
import org.apache.http.ParseException;
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.HttpGet;
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.message.BasicNameValuePair;
import org.apache.http.util.EntityUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import com.alibaba.fastjson.JSONObject;

/**
 * http访问方法实现
 * @author HYJ
 */
public class HttpRequestUtils {
    private static Logger logger = LoggerFactory
            .getLogger(HttpRequestUtils.class); // 日志记录

    /**
     * GET提交
     * @return
     */
    public static String doGet(String url) {
        String strResult = "";
        // 1. 创建一个默认的client实例
        CloseableHttpClient client = HttpClients.createDefault();
        try {
            // 2. 创建一个httpget对象
            HttpGet httpGet = new HttpGet(url);
            System.out.println("executing GET request " + httpGet.getURI());

            // 3. 执行GET请求并获取响应对象
            CloseableHttpResponse resp = client.execute(httpGet);
            try {
                // 6. 打印响应长度和响应内容
                if (resp.getStatusLine().getStatusCode() == HttpStatus.SC_OK) {
                    // 4. 获取响应体
                    HttpEntity entity = resp.getEntity();
                    System.out.println("Response content length = "
                            + entity.getContentLength());
                    System.out.println("------");
                    strResult = EntityUtils.toString(resp.getEntity());
                }
            } finally {
                //无论请求成功与否都要关闭resp
                resp.close();
            }
        } catch (ClientProtocolException e) {
            logger.error("get请求失败:", e);
            // e.printStackTrace();
        } catch (ParseException e) {
            logger.error("get请求解析出错:", e);
            // e.printStackTrace();
        } catch (IOException e) {
            logger.error("get请求IO出错:", e);
            // e.printStackTrace();
        } finally {
            // 8. 最终要关闭连接,释放资源
            try {
                client.close();
            } catch (Exception e) {
                logger.error("get请求完毕关闭连接出错:", e);
                // e.printStackTrace();
            }
        }
        return strResult;
    }

   
    /**
     * json参数方式POST提交
     * @param url
     * @param params
     * @return
     */
    public static String doPost(String url, JSONObject params){
        String strResult = "";
        // 1. 获取默认的client实例
        CloseableHttpClient client = HttpClients.createDefault();
        // 2. 创建httppost实例
        HttpPost httpPost = new HttpPost(url);
        httpPost.addHeader("Content-Type", "application/json;charset=utf-8"); //添加请求头
        try {
            httpPost.setEntity(new StringEntity(params.toJSONString(),"utf-8"));
            CloseableHttpResponse resp = client.execute(httpPost);
            try {
                // 7. 获取响应entity
                HttpEntity respEntity = resp.getEntity();
                strResult = EntityUtils.toString(respEntity, "UTF-8");
            } finally {
                resp.close();
            }
        } catch (ClientProtocolException e) {
            e.printStackTrace();
        } catch (UnsupportedEncodingException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        } finally {
            try {
                client.close();
            } catch (Exception e) {
                e.printStackTrace();
            }
        }
        return strResult;
    }

   /**
     * json参数方式PUT提交
     * @param url
     * @param params
     * @return
     */
    public static String httpPut(String url) {
        String strResult = "";
        // 1. 获取默认的client实例
        CloseableHttpClient client = HttpClients.createDefault();
        // 2. 创建httppost实例
        HttpPut httpPut = new HttpPut(url);
        httpPut.addHeader("Content-Type", "application/json;charset=utf-8"); // 添加请求头try {
            CloseableHttpResponse resp = client.execute(httpPut);
            try {
                // 7. 获取响应entity
                HttpEntity respEntity = resp.getEntity();
                strResult = EntityUtils.toString(respEntity, "UTF-8");
            } finally {
                resp.close();
            }
        } catch (ClientProtocolException e) {
            e.printStackTrace();
        } catch (UnsupportedEncodingException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        } finally {
            try {
                client.close();
            } catch (Exception e) {
                e.printStackTrace();
            }
        }
        return strResult;
    }
    
}

具体封装的数据方法:

//get请求
public
void String accessToken() { String param = "appId=4438770464&secret=50988fde289384edd35588af67bfc8fb&grantType=client_credentials"; String jsonStr = httpGet(uri + "/v1/oauth2/access_token" + "?" + param ); //get请求路径拼接 }
//当请求的参数都是同一级别时可以直接添加参数,如下:post请求
public static void createByThirdPartyUserId(String thirdPartyUserId, String name, String idType, String idNumber, String mobile, String accessToken) { JSONObject jsonParam = new JSONObject(); jsonParam.put("thirdPartyUserId", thirdPartyUserId); jsonParam.put("name", name); jsonParam.put("idType", idType); jsonParam.put("idNumber", idNumber); jsonParam.put("mobile", mobile); String jsonStr = httpPost(uri + "/v1/accounts/createByThirdPartyUserId", jsonParam); }
//当请求的参数是json嵌套的形式,需要进行实体类的设置然后进行转化:post请求
public static void signflows(SignflowsVO signflowsVO) { JSONObject json = (JSONObject) JSON.toJSON(signflowsVO); //json格式数据转化 String jsonStr = httpPost(uri + "/v1/signflows", json); }

请求参数是json嵌套形式的实体类编写,此处只简单举个例子:

public class SignflowsVO {

    private boolean autoArchive;
    
    private String businessScene;
    
    private ConfigInfo configInfo;
        
       //  get,set方法省略
}


package com.example.pojo.e;

public class PlatformSignVO {
    
    private Signfields signfields;

         //  get,set方法省略  
}


//以上两个类构建的是如下的json格式的参数类型,若有包含数组类型的则百度
{
    "autoArchive":false,
    "businessScene":"合同名称",
    "configInfo":{
        "noticeType":"1,2"
    }
}

猜你喜欢

转载自www.cnblogs.com/H-Dream/p/11267053.html