HttpPost方式调用接口的3种方式

2018-09-18 06:35:31来源:博客园 阅读 ()

新老客户大回馈,云服务器低至5折

第一种:需要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;
         
             }

标签:

版权申明:本站文章部分自网络,如有侵权,请联系:west999com@outlook.com
特别注意:本站所有转载文章言论不代表本站观点,本站所提供的摄影照片,插画,设计作品,如需使用,请与原作者联系,版权归原作者所有

上一篇:金九银十,史上最强 Java 面试题整理。

下一篇:Spring Framework的核心:Spring IoC