zoukankan      html  css  js  c++  java
  • 通过HTTP请求调用第三方接口

    通过HTTP请求调用第三方接口

    简单的POST方式

     //json就是url后带的参数,这里是拼接的方式
    
     String json = "{"account_key":"" + account_key + "","secret_code":"" + secret_code+ "","identify_id":"" + identify_id + "","user_labels":"" + user_labels + ""}"
    
    String validUrl = token_url;//需要请求第三方接口的url
    Response res = org.apache.http.client.fluent.Request.Post(validUrl).useExpectContinue().addHeader("mw-token", access_token)//添加Header
                        .bodyString(json, ContentType.APPLICATION_JSON).execute();
                HttpResponse response = res.returnResponse();
                StatusLine statusLine = response.getStatusLine();//获取返回状态
                int statusCode = statusLine.getStatusCode();
                if (statusCode == HttpURLConnection.HTTP_OK) {
                    InputStream is = response.getEntity().getContent();
                    String responseBody = getStreamAsString(is, HTTP.UTF_8);//解析响应返回结果
                    JSONObject jsStr = JSONObject.parseObject(responseBody);
                    int code = jsStr.getIntValue("status");
                    String message = jsStr.getString("msg");
                    if (0 == code) {
                        access_token = jsStr.getString("access_token");
                        logger.info(message);
                    } else {
                        logger.info(message);
                    }
                } else {
                    logger.info("statusCode:" + statusCode);
                }

     解析响应返回结果

    private static String getStreamAsString(InputStream stream, String charset) throws IOException {
            try {
                BufferedReader reader = new BufferedReader(new InputStreamReader(stream, charset), 8192);
                StringWriter writer = new StringWriter();
    
                char[] chars = new char[8192];
                int count = 0;
                while ((count = reader.read(chars)) > 0) {
                    writer.write(chars, 0, count);
                }
    
                return writer.toString();
            } finally {
                if (stream != null) {
                    stream.close();
                }
            }
        }
  • 相关阅读:
    iOS Xcode8的适配
    iOS从生成证书到打包上架-02(详细2016-10最新)
    iOS从生成证书到打包上架-01(详细2016-10最新)
    PHP读取CSV文件
    magento批量导入评论加星
    magento调用static block
    Magento Block的几种调用方式
    JFinal项目中获取根目录
    清除UTF-8编码文件前端的DOM
    PhpStorm注册码(2,3,4,5)通用
  • 原文地址:https://www.cnblogs.com/ouyanxia/p/8206142.html
Copyright © 2011-2022 走看看