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();
                }
            }
        }
  • 相关阅读:
    android stagefright awesomeplayer 分析
    stagefright框架(七)-Audio和Video的同步
    stagefright框架(六)-Audio Playback的流程
    Windows Sockets Error Codes
    编译boost (windows msvc14)
    golang windows程序获取管理员权限(UAC ) via gocn
    阿里云容器服务--配置自定义路由服务应对DDOS攻击
    store / cache 系列
    一些项目感悟
    protobuf-3.0.0-beta-2 windows编译 x64/x86
  • 原文地址:https://www.cnblogs.com/ouyanxia/p/8206142.html
Copyright © 2011-2022 走看看