Android HTTPpost和get請求

/**

  * 發送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;

 }

發佈留言