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 "";
  }
}