zoukankan      html  css  js  c++  java
  • HttpPost方式调用接口的3种方式

    第一种:需要httpclient的依赖包

    <dependency>
    <groupId>org.apache.httpcomponents</groupId>
    <artifactId>httpclient</artifactId>
    <version>4.3.5</version>
    </dependency>

    直接上代码:

    public static String callBgrsjk(String requestParams) {
            String url = null;
            JSONObject jb=new JSONObject();
            jb.put("code",0);
            try {
                CloseableHttpClient httpClient = HttpClients.createDefault();
                RequestConfig requestConfig = RequestConfig.custom()
                        .setSocketTimeout(300 * 1000)
                        .setConnectTimeout(300 * 1000)
                        .build();
                url = "http://URL:Port/地址";
                HttpPost post = new HttpPost(url);
                post.setConfig(requestConfig);
                post.setHeader("Content-Type","application/json;charset=utf-8");
                StringEntity postingString = new StringEntity(requestParams,
                        "utf-8");
                post.setEntity(postingString);
                HttpResponse response = httpClient.execute(post);
                String content = EntityUtils.toString(response.getEntity());
                System.out.println(content);
                return content;
            } catch (SocketTimeoutException e) {
                LoggerUtil.error("调用Dat+"
                        + ".aService接口超时,超时时间:" + 300
                        + "秒,url:" + url + ",参数:" + requestParams, e);
                return jb.toString();
            } catch (Exception e) {
                LoggerUtil.error("调用DataService接口失败,url:" + url + ",参数:" + requestParams,
                        e);
                return jb.toString();
            }
        }

    第二种:使用jdk中的URL

    /**
              * 发送Http post请求
              * 
              * @param xmlInfo
              *            json转化成的字符串
              * @param URL
              *            请求url
              * @return 返回信息
         */
            public static String doHttpPost(String xmlInfo, String URL) {
               System.out.println("发起的数据:" + xmlInfo);
                byte[] xmlData = xmlInfo.getBytes();
                InputStream instr = null;
                java.io.ByteArrayOutputStream out = null;
                try {
                    URL url = new URL(URL);
                    URLConnection urlCon = url.openConnection();
                    urlCon.setDoOutput(true);
                    urlCon.setDoInput(true);
                    urlCon.setUseCaches(false);
                    urlCon.setRequestProperty("content-Type", "application/json");
                    urlCon.setRequestProperty("charset", "utf-8");
                    urlCon.setRequestProperty("Content-length",
                            String.valueOf(xmlData.length));
                    System.out.println(String.valueOf(xmlData.length));
                    DataOutputStream printout = new DataOutputStream(
                            urlCon.getOutputStream());
                    printout.write(xmlData);
                    printout.flush();
                    printout.close();
                    instr = urlCon.getInputStream();
                    byte[] bis = IOUtils.toByteArray(instr);
                    String ResponseString = new String(bis, "UTF-8");
                    if ((ResponseString == null) || ("".equals(ResponseString.trim()))) {
                        System.out.println("返回空");
                    }
                    System.out.println("返回数据为:" + ResponseString);
                    return ResponseString;
        
                } catch (Exception e) {
                    e.printStackTrace();
                    return "0";
                } finally {
                    try {
                        if(out!=null){
                            out.close();
                        }
                        if(instr!=null){
                            instr.close();
                        }
                    } catch (Exception ex) {
                        return "0";
                    }
                }
            }

    第三种:使用apache的commons包

     /**
                  * 发送post请求
                  * 
                  * @param params
                  *            参数
                  * @param requestUrl
                  *            请求地址
                  * @param authorization
                  *            授权书
                  * @return 返回结果
                  * @throws IOException
                  */
                 public static String sendPost(String params, String requestUrl,
                         String authorization) throws IOException {
             
                     byte[] requestBytes = params.getBytes("utf-8"); // 将参数转为二进制流
                     HttpClient httpClient = new HttpClient();// 客户端实例化
                     PostMethod postMethod = new PostMethod(requestUrl);
                     //设置请求头Authorization
                     //postMethod.setRequestHeader("Authorization", "Basic " + authorization);
                     // 设置请求头  Content-Type
                     postMethod.setRequestHeader("Content-Type", "application/json");
                     InputStream inputStream = new ByteArrayInputStream(requestBytes, 0,
                             requestBytes.length);
                     RequestEntity requestEntity = new InputStreamRequestEntity(inputStream,
                             requestBytes.length, "application/json; charset=utf-8"); // 请求体
                     postMethod.setRequestEntity(requestEntity);
                     httpClient.executeMethod(postMethod);// 执行请求
                     InputStream soapResponseStream = postMethod.getResponseBodyAsStream();// 获取返回的流
                     byte[] datas = null;
                     try {
                         datas = readInputStream(soapResponseStream);// 从输入流中读取数据
                     } catch (Exception e) {
                         e.printStackTrace();
                     }
                     String result = new String(datas, "UTF-8");// 将二进制流转为String
                     // 打印返回结果
                     // System.out.println(result);
             
                     return result;
             
                 }
  • 相关阅读:
    Memento模式
    CSS实现半透明div层的方法
    JS解析json数据(如何将json字符串转化为数组)
    并发容器Map之二:ConcurrentNavigableMap
    JSinArray检查数组中是否存在某个值
    Servlet3.0之七:@WebFilter申明该类为过滤器
    Spring源码阅览——BeanFactory体系结构
    使用 Selenium RC 测试 web 应用程序
    函数式编程
    9 个 Java 处理 Exception 的最佳实践
  • 原文地址:https://www.cnblogs.com/feiyangbahu/p/9640261.html
Copyright © 2011-2022 走看看