HttpClient get和post请求的示例代码以及防乱码处理

来源:互联网 发布:域名备案查询工具 编辑:程序博客网 时间:2024/05/17 01:51

请求别人发布的服务我们可能就会使用到HttpClient这个包,HttpClient就是一个支持 HTTP 协议的客户端编程工具包,用来模拟浏览器请求。

  • 乱码解决方法:

就是给HttpGet对象或者HttpPost对象添加头部,如下所示:

//设置请求的报文头部的编码obj.setHeader(new BasicHeader("Content-Type", "application/x-www-form-urlencoded; charset=utf-8"));//设置期望服务端返回的编码obj.setHeader(new BasicHeader("Accept", "text/plain;charset=utf-8"));
  • 1.发布服务

这里我们先发布一个服务用于测试HttpClient的请求,这里发布两个接口,一个用于测试post的一个用于测试get的,springMVC的controller的代码片段如下:

    /**     * 测试httpclient get方法     *      * @param id     * @return     */    @RequestMapping(value = "/api/httpClientTestGet.do", method = RequestMethod.GET)    @ResponseBody    public String httpClientTestGet(String id) {        System.out.println("收到httpclient请求:id=" + id);        return "id为:" + id + "的名字是lijie";    }    /**     * 测试httpclient post方法     *      * @param name     * @param password     * @return     */    @RequestMapping(value = "/api/httpClientTestPost", method = RequestMethod.POST)    @ResponseBody    public String httpClientTestPost(String username, String password) {        System.out.println("name:" + username + " ,password" + password);        return "登陆成功!";    }
  • 2.创建maven工程测试HttpClient的使用

工程结构:

这里写图片描述

pom文件的内容:

<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"    xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">    <modelVersion>4.0.0</modelVersion>    <groupId>httpclient-maven</groupId>    <artifactId>httpclient-maven</artifactId>    <version>0.0.1-SNAPSHOT</version>    <dependencies>        <dependency>            <groupId>jdk.tools</groupId>            <artifactId>jdk.tools</artifactId>            <version>1.7</version>            <scope>system</scope>            <systemPath>${JAVA_HOME}/lib/tools.jar</systemPath>        </dependency>        <dependency>            <groupId>org.apache.httpcomponents</groupId>            <artifactId>httpclient</artifactId>            <version>4.3.6</version>        </dependency>    </dependencies>    <build>        <plugins>            <plugin>                <groupId>org.apache.maven.plugins</groupId>                <artifactId>maven-compiler-plugin</artifactId>                <configuration>                    <source>1.7</source>                    <target>1.7</target>                </configuration>            </plugin>        </plugins>    </build></project>

测试类HttpClientTest代码如下

package com.lijie.hc;import java.util.ArrayList;import java.util.List;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.HttpGet;import org.apache.http.client.methods.HttpPost;import org.apache.http.client.utils.URIBuilder;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.BasicHeader;import org.apache.http.message.BasicNameValuePair;import org.apache.http.util.EntityUtils;/** *  * @author 黎杰 * */public class HttpClientTest {    public static void main(String[] args) throws Exception {        //      testGet();        //      testPost();    }    /**     * httpclient get请求     *      * @throws Exception     */    public static void testGet() throws Exception {        //创建一个httpclient对象        CloseableHttpClient client = HttpClients.createDefault();        //创建URIBuilder        URIBuilder uri = new URIBuilder("http://localhost:8080/api/httpClientTestGet.do");        //设置参数        uri.addParameter("id", "10001");        //创建httpGet对象        HttpGet hg = new HttpGet(uri.build());        //设置请求的报文头部的编码        hg.setHeader(            new BasicHeader("Content-Type", "application/x-www-form-urlencoded; charset=utf-8"));        //设置期望服务端返回的编码        hg.setHeader(new BasicHeader("Accept", "text/plain;charset=utf-8"));        //请求服务        CloseableHttpResponse response = client.execute(hg);        //获取响应码        int statusCode = response.getStatusLine().getStatusCode();        if (statusCode == 200) {            //获取返回实例entity            HttpEntity entity = response.getEntity();            //通过EntityUtils的一个工具方法获取返回内容            String resStr = EntityUtils.toString(entity, "utf-8");            //输出            System.out.println("请求成功,请求返回内容为: " + resStr);        } else {            //输出            System.out.println("请求失败,错误码为: " + statusCode);        }        //关闭response和client        response.close();        client.close();    }    public static void testPost() throws Exception {        //创建一个httpclient对象        CloseableHttpClient client = HttpClients.createDefault();        //创建一个post对象        HttpPost post = new HttpPost("http://localhost:8080/api/httpClientTestPost.do");        //创建一个Entity,模拟表单数据        List<NameValuePair> formList = new ArrayList<>();        //添加表单数据        formList.add(new BasicNameValuePair("username", "黎杰"));        formList.add(new BasicNameValuePair("password", "10086"));        //包装成一个Entity对象        StringEntity entity = new UrlEncodedFormEntity(formList, "utf-8");        //设置请求的内容        post.setEntity(entity);        //设置请求的报文头部的编码        post.setHeader(            new BasicHeader("Content-Type", "application/x-www-form-urlencoded; charset=utf-8"));        //设置期望服务端返回的编码        post.setHeader(new BasicHeader("Accept", "text/plain;charset=utf-8"));        //执行post请求        CloseableHttpResponse response = client.execute(post);        //获取响应码        int statusCode = response.getStatusLine().getStatusCode();        if (statusCode == 200) {            //获取数据            String resStr = EntityUtils.toString(response.getEntity());            //输出            System.out.println("请求成功,请求返回内容为: " + resStr);        } else {            //输出            System.out.println("请求失败,错误码为: " + statusCode);        }        //关闭response和client        response.close();        client.close();    }}

做get请求测试:

服务端收到的请求:

这里写图片描述

客户端收到的请求:

这里写图片描述

做post测试

服务端收到的请求:

这里写图片描述

客户端收到的请求:

这里写图片描述

测试完成!

0 0
原创粉丝点击