天天看点

httpclient发送post请求

import org.apache.http.HttpEntity;
import org.apache.http.NameValuePair;
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 java.io.IOException;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.Set;

public class HttpPostRequestDemo {
    public static void main(String[] args) throws IOException {
        String url = "https://applets-dev.miyapay.com/api/unioncenter/web-background/account/login";
//        HttpGet get = new HttpGet(url);
        CloseableHttpClient hc = HttpClients.createDefault();
//        ------------------------------------------
        //创建body
//        外层使用HashMap的方式传参
        HashMap<String,String> bodyMap = new HashMap<>();
        bodyMap.put("userName","admin3");
        bodyMap.put("password","123456");
//        请求过程需要使用arraylist的方式传递参数,需要进行转换
        ArrayList<NameValuePair> bodyList = new ArrayList<>();
        Set<String> keySet = bodyMap.keySet();
        for(String key:keySet){
            bodyList.add(new BasicNameValuePair(key,bodyMap.get(key)));
        }
        UrlEncodedFormEntity entityBody = new UrlEncodedFormEntity(bodyList);
//        ------------------------------------------
        HttpPost post = new HttpPost(url);
        post.setEntity(entityBody);
        CloseableHttpResponse httpResponse = hc.execute(post);
        HttpEntity responseEntity = httpResponse.getEntity();
        String response = EntityUtils.toString(responseEntity);
        System.out.println(response);

    }
}