สรุป Get | Post request บน android

POST

  1. EditText txtemail = (EditText)findViewById(R.id.txtemail);
  2. EditText txtpassword = (EditText)findViewById(R.id.txtpassword);
  3. HttpPost httpPost = new HttpPost(....url....);
  4. HttpClient client = new DefaultHttpClient();
  5. List<NameValuePair> nameValuePairs = new ArrayList<NameValuePair>();
  6. nameValuePairs.add(new BasicNameValuePair("email", txtemail.getText().toString()));
  7. nameValuePairs.add(new BasicNameValuePair("password", txtpassword.getText().toString()));
  8. httpPost.setEntity(new UrlEncodedFormEntity(nameValuePairs, "UTF-8"));
  9. HttpResponse response = client.execute(httpPost);



GET
  1. HttpClient client = new DefaultHttpClient();
  2. HttpGet httpGet = new HttpGet(.....URL.....);
  3. try {
  4.     HttpResponse response = client.execute(httpGet);
  5.      } catch (ClientProtocolException e) {
  6.                 e.printStackTrace();
  7.      } catch (IOException e) {
  8.                 e.printStackTrace();
  9. }





การอ่านค่าในตัวแปร HttpResponse โดยปกติ


วิธีแรก

  1. InputStream inputStream = response.getEntity().getContent();
  2. BufferedReader reader = new BufferedReader(new InputStreamReader(inputStream));
  3. String line;
  4. while ((line = reader.readLine()) != null) {
  5.        result.append(line);
  6. }


วิธีที่สอง

String result = "";
result = EntityUtils.toString(response.getEntity());




สำหรับเรื่องใช้ Library เข้ามาช่วยแบ่งเบาภาระในงาน GET || POST Request
คงแนะนำที่ง่ายที่สุดคงจะเป็น Ion
Ion จะ Cache HTTP GET Request โดยอัตโนมัติ (ไม่รวมถึง HTTP Post)


result = Ion.with(getApplicationContext()).load(get_target).asString().get();


ยังมีอีกครับ ฝากติดตามอ่านกันได้ที่

4 Libraries for HTTP Request on Android