与第三方接口建立连接并获取返回数据

InputStream inputStream = null;
try {
    String requestUrl = "第三方接口URL";
    String requestMethod = "GET/POST";
    StringBuffer buffer = new StringBuffer();
    URL url = new URL(requestUrl);
    HttpURLConnection httpUrlConnection = (HttpURLConnection) url.openConnection();
    httpUrlConnection.setRequestMethod(requestMethod);
    httpUrlConnection.setDoOutput(true);
    httpUrlConnection.setDoInput(true);
    httpUrlConnection.connect();
    inputStream = httpUrlConnection.getInputStream();
    InputStreamReader inputStreamReader = new
            InputStreamReader(inputStream, "UTF-8");
    BufferedReader bufferReader = new
            BufferedReader(inputStreamReader);
    String str ;
    while ((str = bufferReader.readLine()) != null) {
        buffer.append(str);
    }
    String buffer2str = buffer.toString();
    System.out.println("响应数据:" + buffer2str);
    bufferReader.close();
    inputStreamReader.close();
    inputStream.close();
    inputStream = null;
    httpUrlConnection.disconnect();
}catch (Exception e) {
    e.printStackTrace();
} finally {
    try {
        if (inputStream != null) {
            inputStream.close();
        }
    } catch (IOException ioe) {
        ioe.printStackTrace();
    }
}

你可能感兴趣的:(工具小教程)