Android开发,get ,post请求api

Android开发,get ,post请求api

public class InvokWebApi {
  //Api地址
  private static String srcUrl = "172.16.1.2:8989";

  public static String getUrl() {
    return srcUrl;
  }

  public static void setUrl(String UrlStr) {
    srcUrl = UrlStr;
  }

  /*
   * Get方式调用WebApi接口,参数以Json字符串格式
   * */
  public static String GetParamsJson(String ControllerName, String ActionName, String Parameter) throws Exception{
    String resultString = null;
    HttpURLConnection conn = null;
    InputStream inputStream = null;
    ByteArrayOutputStream bos = null;
    try {
      String urlStr = "http://" + srcUrl +"/" + ControllerName + "/" + ActionName + "?" + Parameter;
      URL url = new URL(urlStr);
      conn = (HttpURLConnection) url.openConnection();
      conn.setReadTimeout(10000);
      conn.setConnectTimeout(10000);
      conn.setRequestMethod("GET");
      conn.setRequestProperty("Content-Type", "application/json");
      conn.setDoInput(true);
      //conn.setDoOutput(true);
      conn.setUseCaches(false);
      conn.setDoOutput(false);
      conn.connect();
//            OutputStream outputStream = conn.getOutputStream();
//            outputStream.write(Parameter.getBytes());
      int responseCode = conn.getResponseCode();
      if (responseCode == 200) {
        if (null != conn.getHeaderField("Content-Encoding")) {
          inputStream = new GZIPInputStream(conn.getInputStream());
        } else {
          inputStream = conn.getInputStream();
        }
        bos = new ByteArrayOutputStream();
        byte[] buffer = new byte[10240];
        int len = -1;
        while ((len = inputStream.read(buffer)) != -1) {
          bos.write(buffer, 0, len);
        }
        bos.flush();
        byte[] resultByte = bos.toByteArray();
        resultString = new String(resultByte);
      } else {
        resultString = "";
      }
    } catch (Exception ex) {
      throw ex;
    } finally {
      if (conn != null) {
        conn.disconnect();
      }
      if (inputStream != null) {
        try {
          inputStream.close();
        } catch (IOException e) {
          throw e;
        }
      }
      if (bos != null) {
        try {
          bos.close();
        } catch (IOException e) {
          throw e;
        }
      }
    }
    return resultString;
  }


  public static String SendPostMessage(String ControllerName, String ActionName, String params) throws Exception{
    StringBuffer buffer = new StringBuffer();
    try {
      if (params != null && !params.isEmpty()) {
//                for (Map.Entry<String, String> entry : params.entrySet()) {
//                    buffer.append(entry.getKey()).append("=").
//                            append(URLEncoder.encode(entry.getValue(), "utf-8")).
//                            append("&");
//                }
//                buffer.deleteCharAt(buffer.length() - 1);
        buffer.append(params);
      }
      byte[] mydata = buffer.toString().getBytes();
      String urlStr = "http://" + srcUrl + "/" + ControllerName + "/" + ActionName;
      URL url = new URL(urlStr);
      HttpURLConnection connection = (HttpURLConnection) url.openConnection();
      connection.setConnectTimeout(3000);
      connection.setDoInput(true);//表示从服务器获取数据
      connection.setDoOutput(true);//表示向服务器写数据
      connection.setRequestMethod("POST");
      connection.setUseCaches(false);
      connection.setRequestProperty("Content-Type", "application/json");//application/x-www-form-urlencoded
      connection.setRequestProperty("Content-Length", String.valueOf(mydata.length));
      connection.connect();
      OutputStream outputStream = connection.getOutputStream();
      outputStream.write(mydata, 0, mydata.length);
      int responseCode = connection.getResponseCode();
      if (responseCode == HttpURLConnection.HTTP_OK) {
        return changeInputeStream(connection.getInputStream(), "utf-8");

      }else{
        return GsonUtils.ToJSON(new OperReturnInfo(0,responseCode+""));
      }

    } catch (UnsupportedEncodingException e) {
      // TODO Auto-generated catch block
      throw e;
    } catch (IOException e) {
      // TODO Auto-generated catch block
      throw e;
    }

  }


  private static String changeInputeStream(InputStream inputStream, String encode) throws Exception {
    //通常叫做内存流,写在内存中的
    ByteArrayOutputStream outputStream = new ByteArrayOutputStream();
    byte[] data = new byte[1024];
    int len = 0;
    String result = "";
    if (inputStream != null) {
      try {
        while ((len = inputStream.read(data)) != -1) {
          data.toString();

          outputStream.write(data, 0, len);
        }
        //result是在服务器端设置的doPost函数中的
        result = new String(outputStream.toByteArray(), encode);
        outputStream.flush();
      } catch (IOException e) {
        // TODO Auto-generated catch block
        throw e;
      }
    }
    return result;
  }

}

  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值