Android - 使用HTTP通訊的範例


由於下列範例是網路上的資源,已經忘記出處,以下作為分享使用。
放在Android端,連線都透過此class執行

  1. public class HTTPconnect {
  2. public String sendPostRequest(String requestURL, HashMap<String, String> postDataParams)
  3. {
  4. URL url;
  5. String response = "";
  6. try {
  7. url = new URL(requestURL);
  8. HttpURLConnection conn = (HttpURLConnection) url.openConnection();/**設定connection物件**/
  9. /**HttpURLConnection是基於HTTP協定的,其底層通過socket通信實現。如果不設置超時(timeout),在網路異常的情況下,可能會導致程式卡住而不繼續往下執行。**/
  10. conn.setReadTimeout(15000);/**單位:毫秒**/
  11. conn.setConnectTimeout(15000);
  12. conn.setRequestMethod("POST");/**選用傳遞方法 >> POST (這樣表單資料傳送過程中不會被明文顯示)**/
  13. conn.setDoInput(true);
  14. conn.setDoOutput(true);
  15. OutputStream os = conn.getOutputStream();
  16. BufferedWriter writer = new BufferedWriter(new OutputStreamWriter(os, "UTF-8"));
  17. writer.write(getPostDataString(postDataParams));
  18. writer.flush();
  19. writer.close();
  20. os.close();
  21. int responseCode=conn.getResponseCode();
  22. if (responseCode == HttpsURLConnection.HTTP_OK)
  23. {
  24. BufferedReader br=new BufferedReader(new InputStreamReader(conn.getInputStream()));
  25. response = br.readLine();
  26. }
  27. else
  28. {
  29. response="Error Create";
  30. }
  31. }
  32. catch (Exception e)
  33. {
  34. e.printStackTrace();
  35. }
  36. return response;
  37. }
  38. private String getPostDataString(HashMap<String, String> params) throws UnsupportedEncodingException {
  39. StringBuilder result = new StringBuilder();
  40. boolean first = true;
  41. for(Map.Entry<String, String> entry : params.entrySet())
  42. {
  43. if (first)
  44. first = false;
  45. else
  46. result.append("&");
  47.  
  48. result.append(URLEncoder.encode(entry.getKey(), "UTF-8"));
  49. result.append("=");
  50. result.append(URLEncoder.encode(entry.getValue(), "UTF-8"));
  51. }
  52. return result.toString();
  53. }
  54. }

留言