基于HttpClient的一个POST通信用法例子

来源:互联网 发布:mac系统如何复制到u盘 编辑:程序博客网 时间:2024/05/18 13:26

在码代码实现之前要先去apache网站上下载httpclient的包,并导入项目中才能正常使用。
然后直接上代码,边看注释边理解吧:

import java.util.ArrayList;import java.util.List;import org.apache.http.HttpEntity;import org.apache.http.HttpResponse;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;//继承自threadpublic class TestPostMethod extends Thread{    //这里的是httpclients,创建一个默认的    HttpClient client=HttpClients.createDefault();    public void run()    {        //url填写自己要发送POST请求的地址        HttpPost post=new HttpPost(URL);        //HttpPost get=new HttpPost("http://www.baidu.com");        try {            //建立一个NameValuePair数组,用于存储欲传送的参数            List<BasicNameValuePair> parameters=new ArrayList<>();            //添加参数            parameters.add(new BasicNameValuePair("key", "value"));            //设置编码,UTF-8            post.setEntity(new UrlEncodedFormEntity(parameters,"UTF-8"));            //执行post,获得返回值            HttpResponse response=client.execute(post);            //用Entity处理            HttpEntity entity=response.getEntity();            //存入String            String result=EntityUtils.toString(entity,"UTF-8");            //然后可以对result进行各种操作了        } catch (Exception e) {            // TODO: handle exception        }    }}
0 0