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

请求别人发布的服务我们可能就会使用到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测试

服务端收到的请求:

这里写图片描述

客户端收到的请求:

这里写图片描述

测试完成!

  • 4
    点赞
  • 9
    收藏
    觉得还不错? 一键收藏
  • 2
    评论
好的,以下是使用HttpClient5发送POST和GET请求的Java代码示例: ```java import org.apache.hc.client5.http.classic.methods.HttpGet; import org.apache.hc.client5.http.classic.methods.HttpPost; import org.apache.hc.client5.http.impl.classic.CloseableHttpClient; import org.apache.hc.client5.http.impl.classic.HttpClients; import org.apache.hc.core5.http.ClassicHttpResponse; import org.apache.hc.core5.http.ContentType; import org.apache.hc.core5.http.io.entity.StringEntity; import java.io.IOException; import java.net.URI; public class HttpClientUtils { /** * 发送GET请求 * * @param url 请求的URL * @return 响应字符串 * @throws IOException */ public static String sendGetRequest(String url) throws IOException { try (CloseableHttpClient httpClient = HttpClients.createDefault()) { HttpGet httpGet = new HttpGet(url); ClassicHttpResponse response = httpClient.execute(httpGet); return response.getEntity().toString(); } } /** * 发送POST请求 * * @param url 请求的URL * @param params 请求参数(JSON格式) * @return 响应字符串 * @throws IOException */ public static String sendPostRequest(String url, String params) throws IOException { try (CloseableHttpClient httpClient = HttpClients.createDefault()) { HttpPost httpPost = new HttpPost(URI.create(url)); StringEntity requestEntity = new StringEntity(params, ContentType.APPLICATION_JSON); httpPost.setEntity(requestEntity); ClassicHttpResponse response = httpClient.execute(httpPost); return response.getEntity().toString(); } } } ``` 这里我们使用了Apache HttpClient5库来发送请求,通过封装成方法,可以方便地在其他地方调用。注意,在使用完CloseableHttpClient后,一定要关闭它,否则可能会导致连接泄露和资源浪费。在上面的示例中,我们使用了try-with-resources语法糖来自动关闭CloseableHttpClient
评论 2
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值