栏目分类:
子分类:
返回
名师互学网用户登录
快速导航关闭
当前搜索
当前分类
子分类
实用工具
热门搜索
名师互学网 > IT > 软件开发 > 后端开发 > Java

使用HttpClient调用接口

Java 更新时间: 发布时间: IT归档 最新发布 模块sitemap 名妆网 法律咨询 聚返吧 英语巴士网 伯小乐 网商动力

使用HttpClient调用接口

HttpClient使用get方式调用接口
    HttpClent端代码
import org.apache.http.HttpEntity;
import org.apache.http.client.methods.CloseableHttpResponse;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClients;
import org.apache.http.util.EntityUtils;
import java.io.IOException;
import java.net.URLEncoder;
import java.nio.charset.StandardCharsets;

public class HttpClientTest {

    public static void main(String[] args) throws Exception {
        //创建httpClient
        CloseableHttpClient httpClient = HttpClients.createDefault();

        // String urlStr="https://www.baidu.com";
        String name = "jjjj+kkk lll|sss";
        //对参数进行编码
        name = URLEncoder.encode(name, StandardCharsets.UTF_8.name());
        String urlStr = "http://localhost:8080/user3?address.province="+name;
       //创建httpGet
        HttpGet httpGet = new HttpGet(urlStr);

       
        httpGet.addHeader("User-Agen", "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/88.0.4324.190 Safari/537.36");
        CloseableHttpResponse httpResponse = null;
        try {

            httpResponse = httpClient.execute(httpGet);
            HttpEntity entity = httpResponse.getEntity();
           
            String string = EntityUtils.toString(entity, "UTF-8");
            
            System.out.println(string);
            EntityUtils.consume(entity);

        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            if (httpClient != null) {
                try {
                    httpClient.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
            if (httpResponse != null) {
                try {
                    httpResponse.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }
    }
}

2.调用的接口

  @RequestMapping("/user3")
   public String user3(User user, HttpServletRequest request) {
       System.out.println(user);
       System.out.println(request.getContentType());
       return "success";
   }    

转载请注明:文章转载自 www.mshxw.com
本文地址:https://www.mshxw.com/it/715882.html
我们一直用心在做
关于我们 文章归档 网站地图 联系我们

版权所有 (c)2021-2022 MSHXW.COM

ICP备案号:晋ICP备2021003244-6号