zoukankan      html  css  js  c++  java
  • JAVA发送POST/GET/PUT/DELETE请求,HEADER传参,BODY参数为JSON格式

    1、maven引入

    <dependency>
       <groupId>org.apache.httpcomponents</groupId>
       <artifactId>httpclient</artifactId>
       <version>4.5</version>
    </dependency>
    
    <dependency>
       <groupId>org.apache.httpcomponents</groupId>
       <artifactId>httpcore</artifactId>
       <version>4.4.4</version>
    </dependency>
    
    <dependency>
       <groupId>org.apache.httpcomponents</groupId>
       <artifactId>httpmime</artifactId>
       <version>4.5</version>
    </dependency>
    
    2、封装post请求方法
    
    public static String httpPost(String url,Map map){
                // 返回body
                String body = null;
                // 获取连接客户端工具
                CloseableHttpClient httpClient = HttpClients.createDefault();
                CloseableHttpResponse httpResponse=null;
                // 2、创建一个HttpPost请求
                HttpPost post = new HttpPost(url);
                // 5、设置header信息
    
       /**header中通用属性*/
        post.setHeader("Accept","*/*");
        post.setHeader("Accept-Encoding","gzip, deflate");
        post.setHeader("Cache-Control","no-cache");
        post.setHeader("Connection", "keep-alive");
        post.setHeader("Content-Type", "application/json;charset=UTF-8");
        /**业务参数*/
        post.setHeader("test1","test1");
        post.setHeader("test2",2);
      
                // 设置参数
                if (map != null) {
        
                    //System.out.println(JSON.toJSONString(map));
                    try {
                        StringEntity entity1=new StringEntity(JSON.toJSONString(map),"UTF-8");
                        entity1.setContentEncoding("UTF-8");
                        entity1.setContentType("application/json");
                        post.setEntity(entity1);
    
                        // 7、执行post请求操作,并拿到结果
                        httpResponse = httpClient.execute(post);
                        // 获取结果实体
                        HttpEntity entity = httpResponse.getEntity();
                        if (entity != null) {
                            // 按指定编码转换结果实体为String类型
                            body = EntityUtils.toString(entity, "UTF-8");
                        }
                        try {
                            httpResponse.close();
                            httpClient.close();
                        } catch (IOException e) {
                            e.printStackTrace();
                        }
                    } catch (Exception e) {
                        e.printStackTrace();
                    }
                }
                return body;
    }
    
    3、封装GET请求方法
    
    
    public static String httpGet(String url){
        // 获取连接客户端工具
        CloseableHttpClient httpClient = HttpClients.createDefault();
        CloseableHttpResponse httpResponse=null;
        String finalString = null;
        HttpGet httpGet = new HttpGet(url);
        /**公共参数添加至httpGet*/
    
    /**header中通用属性*/
        httpGet.setHeader("Accept","*/*");
        httpGet.setHeader("Accept-Encoding","gzip, deflate");
        httpGet.setHeader("Cache-Control","no-cache");
        httpGet.setHeader("Connection", "keep-alive");
        httpGet.setHeader("Content-Type", "application/json;charset=UTF-8");
        /**业务参数*/
        httpGet.setHeader("test1","test1");
        httpGet.setHeader("test2",2);
        try {
            httpResponse = httpClient.execute(httpGet);
            HttpEntity entity = httpResponse.getEntity();
            finalString= EntityUtils.toString(entity, "UTF-8");
            try {
                httpResponse.close();
                httpClient.close();
            } catch (IOException e) {
                e.printStackTrace();
            }
        } catch (IOException e) {
            e.printStackTrace();
        }
        return finalString;
    }
    4、封装put请求
    
    
    public static String httpPut(String url,Map map){
    
        String encode = "utf-8";
    
        //HttpClients.createDefault()等价于 HttpClientBuilder.create().build();
        CloseableHttpClient closeableHttpClient = HttpClients.createDefault();
        HttpPut httpput = new HttpPut(url);
        // 5、设置header信息
    
    /**header中通用属性*/
        httpput.setHeader("Accept","*/*");
        httpput.setHeader("Accept-Encoding","gzip, deflate");
        httpput.setHeader("Cache-Control","no-cache");
        httpput.setHeader("Connection", "keep-alive");
        httpput.setHeader("Content-Type", "application/json;charset=UTF-8");
        /**业务参数*/
        httpput.setHeader("test1","test1");
        httpput.setHeader("test2",2);
        //组织请求参数
        StringEntity stringEntity = new StringEntity(JSON.toJSONString(map), encode);
        httpput.setEntity(stringEntity);
        String content = null;
        CloseableHttpResponse  httpResponse = null;
        try {
            //响应信息
            httpResponse = closeableHttpClient.execute(httpput);
            HttpEntity entity = httpResponse.getEntity();
            content = EntityUtils.toString(entity, encode);
        } catch (Exception e) {
            e.printStackTrace();
        }finally{
            try {
                httpResponse.close();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
        try {
            closeableHttpClient.close();  //关闭连接、释放资源
        } catch (IOException e) {
            e.printStackTrace();
        }
        return content;
    }
    5、封装delete请求
    
    
    public static String httpDelete(String url){
    
        //HttpResponse response = new HttpResponse();
    
         String encode = "utf-8";
    
        String content = null;
        //since 4.3 不再使用 DefaultHttpClient
        CloseableHttpClient closeableHttpClient = HttpClientBuilder.create().build();
        HttpDelete httpdelete = new HttpDelete(url);
        // 5、设置header信息
        
    
    /**header中通用属性*/
        httpdelete.setHeader("Accept","*/*");
        httpdelete.setHeader("Accept-Encoding","gzip, deflate");
        httpdelete.setHeader("Cache-Control","no-cache");
        httpdelete.setHeader("Connection", "keep-alive");
        httpdelete.setHeader("Content-Type", "application/json;charset=UTF-8");
        /**业务参数*/
        httpdelete.setHeader("test1","test1");
        httpdelete.setHeader("test2",2);
        CloseableHttpResponse httpResponse = null;
        try {
            httpResponse = closeableHttpClient.execute(httpdelete);
            HttpEntity entity = httpResponse.getEntity();
            content = EntityUtils.toString(entity, encode);
    
        } catch (Exception e) {
            e.printStackTrace();
        }finally{
            try {
                httpResponse.close();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
        try {   //关闭连接、释放资源
            closeableHttpClient.close();
        } catch (IOException e) {
            e.printStackTrace();
        }
        return content;
    }
  • 相关阅读:
    win7跨网段加域提示"找不到网络路径",解决后又提示"将该计算机的主域DNS更改为“”失败,名称仍然为xx.xx, 错误为“指定的服务器无法运行请求的操作”!
    XP原版系统激活
    使用SQLyog远程连接mysql,错误1130 解决方法
    激活Windows Server 2008 R2 Enterprise 方法
    Non-UTF-8 code starting with 'xff'解决,记录
    Linux 中,基础命令 command not found...问题
    winxp_sp3未激活的登录问题
    linux安装tomcat
    Notepad++ 配置python
    python idle 清屏问题的解决
  • 原文地址:https://www.cnblogs.com/telwanggs/p/14169276.html
Copyright © 2011-2022 走看看