• java http的get、post、post json参数的方法


    对于http的post json参数方法使用的是Apache的HttpClient-4.x.Jar,先引入jar

    在maven添加如下:

          <!-- https://mvnrepository.com/artifact/org.apache.httpcomponents/httpclient -->
       <dependency>
        <groupId>org.apache.httpcomponents</groupId>
        <artifactId>httpclient</artifactId>
        <version>4.5.12</version>
      </dependency>

    使用Apache的HttpClient-4.x.Jar包。

    Jar包Maven下载地址:https://mvnrepository.com/artifact/org.apache.httpcomponents/httpclient

    1、先创建HttpUtil 工具类:

    package com.game.www.utils;
    
    import java.io.BufferedReader;
    import java.io.IOException;
    import java.io.InputStream;
    import java.io.InputStreamReader;
    import java.io.OutputStream;
    import java.net.HttpURLConnection;
    import java.net.MalformedURLException;
    import java.net.URL;
    
    import org.apache.http.HttpResponse;
    import org.apache.http.HttpStatus;
    import org.apache.http.client.methods.HttpPost;
    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.protocol.HTTP;
    
    import com.alibaba.fastjson.JSONObject;
    
    public class HttpUtil {
    
        
        public static String doGet(String httpurl) {
            
            HttpURLConnection connection = null;
            InputStream is = null;
            BufferedReader br = null;
            String result = null;// 返回结果字符串
            try {
                // 创建远程url连接对象
                URL url = new URL(httpurl);
                // 通过远程url连接对象打开一个连接,强转成httpURLConnection类
                connection = (HttpURLConnection) url.openConnection();
                // 设置连接方式:get
                connection.setRequestMethod("GET");
                // 设置连接主机服务器的超时时间:15000毫秒
                connection.setConnectTimeout(15000);
                // 设置读取远程返回的数据时间:60000毫秒
                connection.setReadTimeout(60000);
                // 发送请求
                connection.connect();
                // 通过connection连接,获取输入流
                if (connection.getResponseCode() == 200) {
                    is = connection.getInputStream();
                    // 封装输入流is,并指定字符集
                    br = new BufferedReader(new InputStreamReader(is, "UTF-8"));
                    // 存放数据
                    StringBuffer sbf = new StringBuffer();
                    String temp = null;
                    while ((temp = br.readLine()) != null) {
                        sbf.append(temp);
                        sbf.append("
    ");
                    }
                    result = sbf.toString();
                }
            } catch (MalformedURLException e) {
                e.printStackTrace();
            } catch (IOException e) {
                e.printStackTrace();
            } finally {
                // 关闭资源
                if (null != br) {
                    try {
                        br.close();
                    } catch (IOException e) {
                        e.printStackTrace();
                    }
                }
     
                if (null != is) {
                    try {
                        is.close();
                    } catch (IOException e) {
                        e.printStackTrace();
                    }
                }
     
                connection.disconnect();// 关闭远程连接
            }
     
            return result;
        }
        
    
        public static String doPost(String httpUrl, String param) {
     
            HttpURLConnection connection = null;
            InputStream is = null;
            OutputStream os = null;
            BufferedReader br = null;
            String result = null;
            try {
                URL url = new URL(httpUrl);
                // 通过远程url连接对象打开连接
                connection = (HttpURLConnection) url.openConnection();
                // 设置连接请求方式
                connection.setRequestMethod("POST");
                // 设置连接主机服务器超时时间:15000毫秒
                connection.setConnectTimeout(150000);
                // 设置读取主机服务器返回数据超时时间:60000毫秒
                connection.setReadTimeout(600000);
     
                // 默认值为:false,当向远程服务器传送数据/写数据时,需要设置为true
                connection.setDoOutput(true);
                // 默认值为:true,当前向远程服务读取数据时,设置为true,该参数可有可无
                connection.setDoInput(true);
                // 设置传入参数的格式:请求参数应该是 name1=value1&name2=value2 的形式。
                connection.setRequestProperty("Content-Type",
                        "application/x-www-form-urlencoded");
                // 设置鉴权信息:Authorization: Bearer da3efcbf-0845-4fe3-8aba-ee040be542c0
                connection.setRequestProperty("Authorization",
                        "Bearer da3efcbf-0845-4fe3-8aba-ee040be542c0");
                // 通过连接对象获取一个输出流
                os = connection.getOutputStream();
                // 通过输出流对象将参数写出去/传输出去,它是通过字节数组写出的
                os.write(param.getBytes());
                // 通过连接对象获取一个输入流,向远程读取
                if (connection.getResponseCode() == 200) {
                    is = connection.getInputStream();
                    // 对输入流对象进行包装:charset根据工作项目组的要求来设置
                    br = new BufferedReader(new InputStreamReader(is, "UTF-8"));
     
                    StringBuffer sbf = new StringBuffer();
                    String temp = null;
                    // 循环遍历一行一行读取数据
                    while ((temp = br.readLine()) != null) {
                        sbf.append(temp);
                        sbf.append("
    ");
                    }
                    result = sbf.toString();
                }
            } catch (MalformedURLException e) {
                e.printStackTrace();
            } catch (IOException e) {
                e.printStackTrace();
            } finally {
                // 关闭资源
                if (null != br) {
                    try {
                        br.close();
                    } catch (IOException e) {
                        e.printStackTrace();
                    }
                }
                if (null != os) {
                    try {
                        os.close();
                    } catch (IOException e) {
                        e.printStackTrace();
                    }
                }
                if (null != is) {
                    try {
                        is.close();
                    } catch (IOException e) {
                        e.printStackTrace();
                    }
                }
                // 断开与远程地址url的连接
                connection.disconnect();
            }
            return result;
        }
        
        /**
         * 发送post请求
         * @param URL
         * @param json
         *
         * @return
         */
        public static String sendPost(String URL,JSONObject json) {
            CloseableHttpClient client = HttpClients.createDefault();
            HttpPost post = new HttpPost(URL);
            post.setHeader("Content-Type", "application/json");
            post.addHeader("Authorization", "Basic YWRtaW46");
            String result;
            try {
                StringEntity s = new StringEntity(json.toString(), "utf-8");
                s.setContentEncoding(new BasicHeader(HTTP.CONTENT_TYPE,
                        "application/json"));
                post.setEntity(s);
                // 发送请求
                HttpResponse httpResponse = client.execute(post);
                // 获取响应输入流
                InputStream inStream = httpResponse.getEntity().getContent();
                BufferedReader reader = new BufferedReader(new InputStreamReader(
                        inStream, "utf-8"));
                StringBuilder strber = new StringBuilder();
                String line;
                while ((line = reader.readLine()) != null)
                    strber.append(line + "
    ");
                inStream.close();
                result = strber.toString();
                if (httpResponse.getStatusLine().getStatusCode() == HttpStatus.SC_OK) {
                    System.out.println("请求服务器成功,做相应处理");
                } else {
                    System.out.println("请求服务端失败");
                }
            } catch (Exception e) {
    //            logger.error("请求异常:"+e.getMessage());
                throw new RuntimeException(e);
            }
            return result;
        }
        
        
    }

    2、spring mvc 的controller 测试案例:

        @RequestMapping(value = "/get", method = RequestMethod.GET, produces = "text/html;charset=UTF-8")
        @ResponseBody
        @ApiOperation(value = "get", notes = "get")
        @ApiResponse(response= String.class, code = 200, message = "接口返回对象参数")
        public String get(HttpServletRequest request, HttpServletResponse response) {
            
            try {
                String url = "http://11.29.11.19:8080/Inv/baseData/action/getList";
                String result = HttpUtil.doGet(url);
                
                return result;
            
            } catch (Exception e) {
                e.printStackTrace();
                return "fail";
            }
        }
        
        @RequestMapping(value = "/post", method = RequestMethod.GET, produces = "text/html;charset=UTF-8")
        @ResponseBody
        @ApiOperation(value = "post", notes = "post")
        @ApiResponse(response= String.class, code = 200, message = "接口返回对象参数")
        public String post(HttpServletRequest request, HttpServletResponse response) {
            
            try {
                String url = "http://11.29.11.19:8080/Inv/baseData/action/query";
                String p = "limit=10&offset=2";
                String result = HttpUtil.doPost(url, p);
            
                return result;
            
            } catch (Exception e) {
                e.printStackTrace();
                return "fail";
            }
        }
        
        
        @RequestMapping(value = "/postJson", method = RequestMethod.GET, produces = "text/html;charset=UTF-8")
        @ResponseBody
        @ApiOperation(value = "postJson", notes = "postJson")
        @ApiResponse(response= String.class, code = 200, message = "接口返回对象参数")
        public String postJson(HttpServletRequest request, HttpServletResponse response) {
            
            try {
                String url = "http://11.29.11.19:8080/my/api/user/login";
                
                JSONObject jsonObject = new JSONObject();
                
                jsonObject.put("loginname", "123456");
                jsonObject.put("pwd", "123456");
                String result = HttpUtil.sendPost(url,jsonObject);
            
                return result;
            
            } catch (Exception e) {
                e.printStackTrace();
                return "fail";
            }
        }
        
        
  • 相关阅读:
    Numpy数据处理函数
    数据库-创建表
    描述统计学:表格法和图形法
    最短路 || POJ 1511 Invitation Cards
    搜索 || DFS || UOJ 146 信息传递
    最短路 || UOJ 19 寻找道路
    最短路 || POJ 1847 Tram
    博弈论
    筛选法 || POJ 3292 Semi-prime H-numbers
    团队第一次作业
  • 原文地址:https://www.cnblogs.com/zoro-zero/p/13441327.html
Copyright © 2020-2023  润新知