关闭

Java调用Http请求

标签: javaHTTP请求接口
184人阅读 评论(0) 收藏 举报
分类:
package test;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.OutputStreamWriter;
import java.net.HttpURLConnection;
import java.net.URL;

public class HttpInvokeUtils {

  /**
   * 
   * @param getUrl
   *        接口地址(已拼接参数)
   * @return 接口调用返回参数
   */
  public static String invokeContentFromGet(String getUrl) {
    try {
      URL url = new URL(getUrl);
      HttpURLConnection conn = (HttpURLConnection) url.openConnection();
      // 获取响应状态
      if (conn.getResponseCode() != HttpURLConnection.HTTP_OK) {
        System.out.println("连接接口地址失败!");
        return "";
      }
      // 获取响应内容体
      String line, result = "";
      BufferedReader in = new BufferedReader(new InputStreamReader(conn.getInputStream(), "utf-8"));
      while ((line = in.readLine()) != null) {
        result += line;
      }
      in.close();
      return result;
    }
    catch (Exception e) {
      System.err.println("接口调用失败:" + e.getMessage());
    }
    return "";
  }

  /***
   * post方式调用接口
   * 
   * @param postUrl
   *        接口地址
   * @param postData
   *        接口参数
   * @return 接口调用返回参数
   */
  public static String invokeContentFromPost(String postUrl, String postData) {
    try {
      URL url = new URL(postUrl);
      HttpURLConnection conn = (HttpURLConnection) url.openConnection();
      conn.setRequestMethod("POST");
      conn.setRequestProperty("Content-Type", "application/x-www-form-urlencoded");
      conn.setRequestProperty("Connection", "Keep-Alive");
      conn.setUseCaches(false);
      conn.setDoOutput(true);
      conn.setRequestProperty("Content-Length", "" + postData.length());
      OutputStreamWriter out = new OutputStreamWriter(conn.getOutputStream(), "UTF-8");
      out.write(postData);
      out.flush();
      out.close();
      // 获取响应状态
      if (conn.getResponseCode() != HttpURLConnection.HTTP_OK) {
        System.out.println("连接接口地址失败!");
        return "";
      }
      // 获取响应内容体
      String line, result = "";
      BufferedReader in = new BufferedReader(new InputStreamReader(conn.getInputStream(), "utf-8"));
      while ((line = in.readLine()) != null) {
        result += line;
      }
      in.close();
      return result;
    }
    catch (IOException e) {
      System.out.println("接口调用失败!" + e.getMessage());
    }
    return "";
  }
}
5
0

查看评论
* 以上用户言论只代表其个人观点,不代表CSDN网站的观点或立场
    个人资料
    • 访问:5425次
    • 积分:99
    • 等级:
    • 排名:千里之外
    • 原创:4篇
    • 转载:2篇
    • 译文:0篇
    • 评论:0条
    文章分类
    文章存档