欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页

使用httpclient提交post请求

程序员文章站 2022-05-30 21:43:03
...


import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.NameValuePair;
import org.apache.http.client.HttpClient;
import org.apache.http.client.entity.UrlEncodedFormEntity;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.impl.client.HttpClients;
import org.apache.http.message.BasicNameValuePair;
import org.apache.http.util.EntityUtils;

//使用httpclient提交post请求 x-www-form-urlencoded 
public class PostTest{
 
    public static void main(String[] args) throws Exception {
    String url="http://localhost:8080/boot/user/";
    Map<String,Object> params=new HashMap<String,Object>();
    params.put("a", "1");
    String result=post(url,params);
        System.out.println(result);
    }
    
    public static String post(String url, Map<String,Object> params){
        HttpClient client = HttpClients.createDefault();
        HttpPost hp=new HttpPost(url);
        String s="";
        try {
        List<NameValuePair> names=new ArrayList<NameValuePair>();
        Set<String> keys=params.keySet();
        for(String k:keys) {
        names.add(new BasicNameValuePair(k, params.get(k).toString()));
        }
        hp.setEntity(new UrlEncodedFormEntity(names,"UTF-8"));
        hp.setHeader("Content-type", "application/x-www-form-urlencoded");
        HttpResponse response=client.execute(hp);
        int status=response.getStatusLine().getStatusCode();
        if(status==200) {
        HttpEntity entity=response.getEntity();
        s=EntityUtils.toString(entity);
        }
       
        }catch(Exception e) {
        e.printStackTrace();
        }
        return s;
    } 
}
相关标签: java httpclient