通过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();
            }
        }
    }

 

posted on 2018-01-05 18:07  依米欧  阅读(10673)  评论(0编辑  收藏  举报