20.11.2016 Views

ANDROID APP

You also want an ePaper? Increase the reach of your titles

YUMPU automatically turns print PDFs into web optimized ePapers that Google loves.

กรรมวิธี: การใช้งาน HTTP POST<br />

ในบางครั้งเราอาจต้องการอ่านข้อมูลประเภทไบนารี (Binary) จาากอินเตอร์เน็ต เช่น รูปภาพ<br />

วิดีโอ รวมถึงไฟล์เสียงต่างๆ ถ้าเป็นแบบนั้นก็ให้ใช้คำสั่ง setRequestMethod() เพื่อใช้งาน<br />

โปรโตคอล HTTP POST โดยใช้ setRequestMethod() เช่น<br />

httpconn.setRequestMethod(POST);<br />

การทำางานกับข้อมูลบนเว็บ<br />

การอ่านข้อมูลจากอินเตอร์เน็ตอาจใช้ระยะเวลานาน คาดเดาไม่ได้ ดังนั้นเราจะดึงเธรดย่อยมา<br />

ช่วยทำงานในส่วนนี้เพื่อไม่ให้เกิดอาการแอพค้างในระหว่างที่กำลังอ่านข้อมูลอยู่<br />

การสร้างเธรดเบื้องหลังเพื่อทำงานเหล่านี้นั้น ในระบบปฏิบัติการแอนดรอยด์มีคำสั่ง Async-<br />

Task เพื่อใช้ทำงานแบบเบื้องหลัง และส่งผลลัพธ์ไปยังเธรดของ UI โดยไม่จำเป็นต้องสร้างเธรดขึ้น<br />

มาเอง ดังนั้นเราจึงสามารถนำเมธอด POST ไปใช้งานร่วมกับแอคทิวิตี้หลักได้ ดังนี้<br />

private class mygoogleSearch extends AsyncTask {<br />

209<br />

protected String doInBackground(String... searchKey) {<br />

String key = searchKey[0];<br />

}<br />

try {<br />

return SearchRequest(key);<br />

} catch(Exception e) {<br />

Log.v(“Exception google search”,<br />

“Exception:”+e.getMessage());<br />

return “”;<br />

}<br />

}<br />

protected void onPostExecute(String result) {<br />

try {<br />

ProcessResponse(result);<br />

} catch(Exception e) {<br />

Log.v(“Exception google search”,<br />

“Exception:”+e.getMessage());<br />

}<br />

}<br />

คำสั่งนี้สามารถนำไปเพิ่มต่อท้ายคำสั่งในไฟล์ GoogleSearch.java ในชุดคำสั่งที่ 8.6 ได้<br />

ซึ่งผลลัพธ์ที่ได้ก็จะเหมือนกับในตัวอย่างก่อนหน้านี้ และมีการเปลี่ยนแปลงในส่วนท้ายของ onClick-<br />

Listener ดังนี้<br />

new mygoogleSearch().execute(ed1.getText().toString());

Hooray! Your file is uploaded and ready to be published.

Saved successfully!

Ooh no, something went wrong!