Java调用Http请求

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 "";
  }
}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值