现在的位置: 首页 > 移动开发 > 正文

Android HTTPpost和get请求

2018年09月18日 移动开发 ⁄ 共 1881字 ⁄ 字号 评论关闭

/**
  * 发送Post请求
  *
  * @param path
  *            请求路径
  * @param params
  *            请求参数
  * @param encoding
  *            编码
  * @return 服务器返回流
  */
 public static InputStream sendPOSTRequest(String url,
   Map<String, String> params, String encoding) throws Exception {
  StringBuilder data = new StringBuilder();
  if (params != null && !params.isEmpty()) {
   for (Map.Entry<String, String> entry : params.entrySet()) {
    data.append(entry.getKey()).append("=");
    data.append(URLEncoder.encode(entry.getValue(), encoding));
    data.append("&");
   }
   data.deleteCharAt(data.length() - 1);
  }
  byte[] entity = data.toString().getBytes();// 生成实体数据
  HttpURLConnection conn = (HttpURLConnection) new URL(url)
    .openConnection();
  conn.setConnectTimeout(5000);
  conn.setRequestMethod("POST");
  conn.setDoOutput(true);// 允许对外输出数据
  conn.setRequestProperty("Content-Type",
    "application/x-www-form-urlencoded");
  conn.setRequestProperty("Content-Length", String.valueOf(entity.length));
  OutputStream outStream = conn.getOutputStream();
  outStream.write(entity);
  if (conn.getResponseCode() == 200) {
   return conn.getInputStream();
  }
  return null;
 }

 /**
  * 发送get请求的方法
  * @param url
  * @param params
  * @param encoding
  * @return
  * @throws Exception
  */
 public static InputStream sendGETRuqest(String url,
   Map<String, String> params, String encoding) throws Exception {
  // StringBuilder是用来组拼请求地址和参数

  StringBuilder sb = new StringBuilder();

  sb.append(url).append("?");

  if (params != null && params.size() != 0) {

   for (Map.Entry<String, String> entry : params.entrySet()) {

    // 如果请求参数中有中文,需要进行URLEncoder编码
    sb.append(entry.getKey()).append("=")
      .append(URLEncoder.encode(entry.getValue(), encoding));

    sb.append("&");
   }

   sb.deleteCharAt(sb.length() - 1);

  }

  HttpURLConnection conn = (HttpURLConnection) new URL(sb.toString())
    .openConnection();

  conn.setConnectTimeout(5000);

  conn.setRequestMethod("GET");

  if (conn.getResponseCode() == 200) {

   return conn.getInputStream();

  }

  return null;
 }

抱歉!评论已关闭.