http post 方法传递参数的2种方式

StringEntity

try{  

    HttpPost httpPost = new HttpPost(url);  

    //param参数,可以为param="key1=value1&key2=value2"的一串字符串,或者是jsonObject 

     String param1="key1=value1&key2=value2"

	JSONObject param2= new JSONObject();  

    param2.put("key1", "value1");  

    param2.put("key2t"," value2");  

    StringEntity stringEntity = new StringEntity(param1);  

    StringEntity stringEntity = new StringEntity(param2.toString());  

    stringEntity.setContentType("application/x-www-form-urlencoded");  

    httpPost.setEntity(stringEntity);  

    HttpClient client = new DefaultHttpClient();   

    HttpResponse httpResponse = client.execute(httpPost);  

    String result = EntityUtils.toString(httpResponse.getEntity(), HTTP.UTF_8);  

} catch(IOException e){  

}  

UrlEncodedFormEntity

// An highlighted block

List<NameValuePair> pairs = new ArrayList<NameValuePair>();  

NameValuePair pair1 = new BasicNameValuePair("supervisor", supervisorEt.getEditableText().toString());  

NameValuePair pair2 = new BasicNameValuePair("content", superviseContentEt.getEditableText().toString());  

NameValuePair pair3 = new BasicNameValuePair("userId", String.valueOf(signedUser.getId()));  

pairs.add(pair1);  

pairs.add(pair2);  

pairs.add(pair3);  

httpPost.setEntity(new UrlEncodedFormEntity(pairs, HTTP.UTF_8)) 

项目实例

需要导入的jar包
在这里插入图片描述

import com.dtstack.flinkx.exception.WriteRecordException;
import com.dtstack.flinkx.outputformat.BaseRichOutputFormat;
import com.dtstack.flinkx.restapi.common.HttpUtil;
import com.dtstack.flinkx.util.ExceptionUtil;
import com.google.common.collect.Maps;
import com.google.gson.Gson;
import com.google.gson.GsonBuilder;
import org.apache.flink.types.Row;
import org.apache.http.HttpStatus;
import org.apache.http.client.config.RequestConfig;
import org.apache.http.client.methods.CloseableHttpResponse;
import org.apache.http.client.methods.HttpRequestBase;
import org.apache.http.impl.client.CloseableHttpClient;

import java.io.IOException;
import java.util.*;

//getRequest

HttpRequestBase request = HttpUtil.getRequest(method, requestBody, header, url);
/* 20210803 wx 修改post访问api josn参数无法传输的问题*/
    public static HttpRequestBase getRequest(String method,
                                             Map<String, Object> requestBody,
                                             Map<String, String> header,
                                             String url) {
        LOG.debug("current request url: {}  current method:{} \n", url, method);
        HttpRequestBase request = null;
        if (HttpMethod.GET.name().equalsIgnoreCase(method)) {
            request = new HttpGet(url);
        } else if (HttpMethod.POST.name().equalsIgnoreCase(method)) {
            HttpPost post = new HttpPost(url);
            post.setEntity(getEntityData(requestBody));
            request = post;
        } else {
            throw new UnsupportedOperationException("Unsupported method:" + method);
        }

        for (Map.Entry<String, String> entry : header.entrySet()) {
            request.addHeader(entry.getKey(), entry.getValue());
        }

        return request;
    }

//getEntityData

post.setEntity(getEntityData(requestBody));
public static StringEntity getEntityData(Map<String, Object> body) {
    String params =  jsonToParams(String.valueOf(gson.toJson(body.get("json"))));
    StringEntity stringEntity = new StringEntity(params, StandardCharsets.UTF_8);
    //stringEntity.setContentEncoding(StandardCharsets.UTF_8.name());这里设置了UTF-8反而不可以了
    return stringEntity;
}

//jsonToParams

String params =  jsonToParams(String.valueOf(gson.toJson(body.get("json"))));
/**
     * 20210803
     * json 转化为params 的格式 param参数,可以为"key1=value1&key2=value2"的一串字符串
     * @param jsonStr
     * @return
     */
    public static String jsonToParams(String jsonStr){
        String params = null;
        try {
            Map<String,Object> map2= JSONObject.parseObject(jsonStr, HashMap.class);
            for (Map.Entry<String, Object> entry : map2.entrySet()) {
                System.out.println("key= " + entry.getKey() + " and value= " + entry.getValue());
                if(params==null){
                    params = entry.getKey()+"="+String.valueOf(entry.getValue());
                }else{
                    params = params +"&"+ entry.getKey()+"="+String.valueOf(entry.getValue());
                }
            }
            return params;
        }catch (Exception ex){
            throw new RuntimeException("json转map出错------------------------------------------------------------",ex);
        }
    }
Logo

加入社区!打开量化的大门,首批课程上线啦!

更多推荐