Android and OkHttp (HTTP LIB:Library) |
Android and OkHttp (HTTP LIB:Library) อีก Library ตัวหนึ่งในการเขียน Android App ที่น่าสนใจไว้สำหรับการจัดการในการเชื่อมต่อกับ Http คือ OkHttp โดยไลบรารี่ตัวนี้ค่อนข้างจะทำงานได้ดีในระดับหนึ่ง ความสามารถพื้นฐานรองรับการการรับ-ส่งข้อมูลในรูปแบบ Get และ Post สามารถส่งได้ทั้งที่เป็น String , Multipart File , Streaming และอื่น ๆ อีกหลายฟีเจอร์ สั่งความสามารถพิเศษที่น่าจะสนใจ คือจะใช้ Gson ทั้งการ รับและส่ง ได้เช่นเดียวกัน
Android and OkHttp
ในการเขียน Android App ช่วงหลัง ๆ ผมจึงแนะนำให้ใช้ Library มาเข้าจัดการกับเรื่องเหล่านี้แทน ซึ่งในปัจจุบันมี Library หลายตัวมาก ที่เข้ามาจัดการกับ Http โดยเฉพาะ รองรับการทำงานเกือบทุกรูปแบบ ไม่ว่าจะเป็น get, post การรับส่ง string , files หรือแม้แต่ json ก็ยังถูกนำมารวมใช้งานกับ library นี้ด้วย โดยที่เราไม่จำเป็นจะต้องใช้การ parser ค่ามันอีก เพราะมันจะแปลงมาเป็น json ให้เลย ทั้ง ไป-กลับ และ function ต่าง ๆ ที่อยู่ใน Library เราจะมั่นใจได้ว่ามันจะไม่ถูก deprecated แน่นอน เพราะถ้ามีการ deprecated เราก็จะสามารถอัพเดดเวอร์ชั่นใหม่ ๆ ได้ตลอด โดยที่ไม่จำเป็นจะต้องมาแก้ไข Code ใหม่
สำหรับตัวอย่างและ Code นี้รองรับการเขียนทั้งบนโปรแกรม Eclipse และ Android Studio
Download OkHttp
![Android and Glide Android and Glide](https://www.thaicreate.com/upload/tutorial/android-okhttp-02.jpg?v=1001)
การติดตั้งสามารถดาวน์โหลดไฟล์ .JAR แล้วนำไป Import ลงใน Eclipse หรือ Android Studio
![Android and Glide Android and Glide](https://www.thaicreate.com/upload/tutorial/android-okhttp-03.jpg?v=1001)
ในการใช้งาน OkHttp จะต้องใช้ Library ของ okio ด้วย และจะรองรับ Level 19 หรือ Android 4.4.2 (เวอร์ชั่นต่ำกว่านี้น่าจะได้)
กรณีใช้บน Android Studio เพิ่ม build.gradle
compile 'com.squareup.okhttp:okhttp:2.6.0'
compile 'com.squareup.okio:okio:1.6.0'
ใน AndroidManifest.xml เพิ่ม Permission สำหรับการเชื่อมต่อกับ Internet ดังนี้
<uses-permission android:name="android.permission.INTERNET" />
ขั้นตอนการเรียกใช้
Example 1 : การเรียก URL ผ่าน get
Syntax
OkHttpClient client = new OkHttpClient();
String run(String url) throws IOException {
Request request = new Request.Builder()
.url(url)
.build();
Response response = client.newCall(request).execute();
return response.body().string();
}
getString.php : ตัวอย่างไฟล์ PHP ที่อยู่บน Server (www.thaicreate.com/android/getString.php)
<?php
echo date("Y-m-d H:i:s");
?>
![Android and Glide Android and Glide](https://www.thaicreate.com/upload/tutorial/android-okhttp-04.jpg?v=1001)
activity_main.xml
<TableLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent" >
<TextView
android:id="@+id/txtResult"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_marginTop="50dp"
android:gravity="center"
android:text="Result" />
</TableLayout>
![](/images/adv.jpg)
MainActivity.java
package com.myapp;
import android.os.Bundle;
import android.os.StrictMode;
import java.io.IOException;
import com.squareup.okhttp.OkHttpClient;
import com.squareup.okhttp.Request;
import com.squareup.okhttp.Response;
import android.app.Activity;
import android.widget.TextView;
public class MainActivity extends Activity {
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
// Permission StrictMode
if (android.os.Build.VERSION.SDK_INT > 9) {
StrictMode.ThreadPolicy policy = new StrictMode.ThreadPolicy.Builder().permitAll().build();
StrictMode.setThreadPolicy(policy);
}
final TextView txtResult = (TextView) findViewById(R.id.txtResult);
getHttp http = new getHttp();
String response = null;
try {
response = http.run("https://www.thaicreate.com/android/getString.php");
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
txtResult.setText(response);
}
public class getHttp {
OkHttpClient client = new OkHttpClient();
String run(String url) throws IOException {
Request request = new Request.Builder()
.url(url)
.build();
Response response = client.newCall(request).execute();
return response.body().string();
}
}
}
![Android and Glide Android and Glide](https://www.thaicreate.com/upload/tutorial/android-okhttp-05.jpg?v=1001)
Example 2 : การเรียก URL และส่งค่า Parameters ผ่าน post
Syntax
private final OkHttpClient client = new OkHttpClient();
public void run() throws Exception {
RequestBody formBody = new FormEncodingBuilder()
.add("search", "Jurassic Park")
.build();
Request request = new Request.Builder()
.url("https://en.wikipedia.org/w/index.php")
.post(formBody)
.build();
Response response = client.newCall(request).execute();
if (!response.isSuccessful()) throw new IOException("Unexpected code " + response);
System.out.println(response.body().string());
}
postString.php : ตัวอย่างไฟล์ PHP ที่อยู่บน Server (www.thaicreate.com/android/postString.php)
<?php
echo "Sawatdee : ".$_POST["sName"]." ".$_POST["sLastName"];
?>
activity_main.xml
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent" >
<TextView
android:id="@+id/txtResult"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignParentTop="true"
android:layout_centerHorizontal="true"
android:layout_marginTop="107dp"
android:text="Result" />
</RelativeLayout>
MainActivity.java
package com.myapp;
import android.os.Bundle;
import android.os.StrictMode;
import java.io.IOException;
import com.squareup.okhttp.FormEncodingBuilder;
import com.squareup.okhttp.OkHttpClient;
import com.squareup.okhttp.Request;
import com.squareup.okhttp.RequestBody;
import com.squareup.okhttp.Response;
import android.app.Activity;
import android.widget.TextView;
public class MainActivity extends Activity {
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
// Permission StrictMode
if (android.os.Build.VERSION.SDK_INT > 9) {
StrictMode.ThreadPolicy policy = new StrictMode.ThreadPolicy.Builder().permitAll().build();
StrictMode.setThreadPolicy(policy);
}
final TextView txtResult = (TextView) findViewById(R.id.txtResult);
postHttp http = new postHttp();
RequestBody formBody = new FormEncodingBuilder()
.add("sName", "Weerachai")
.add("sLastName", "Nukitram")
.build();
String response = null;
try {
response = http.run("https://www.thaicreate.com/android/postString.php",formBody);
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
txtResult.setText(response);
}
public class postHttp {
OkHttpClient client = new OkHttpClient();
String run(String url,RequestBody body) throws IOException {
Request request = new Request.Builder()
.url(url)
.post(body)
.build();
Response response = client.newCall(request).execute();
return response.body().string();
}
}
}
![Android and Glide Android and Glide](https://www.thaicreate.com/upload/tutorial/android-okhttp-06.jpg?v=1001)
![](/images/adv.jpg)
Example 3 : การส่งค่า Post ไปยัง Web Server พร้อมกับ multipart/form-data
public static final MediaType MEDIA_TYPE_MARKDOWN = MediaType.parse("text/x-markdown; charset=utf-8");
private final OkHttpClient client = new OkHttpClient();
public void run() throws Exception {
File file = new File("/mnt/README.md");
Request request = new Request.Builder()
.url("https://api.github.com/markdown/raw")
.post(RequestBody.create(MEDIA_TYPE_MARKDOWN, file))
.build();
Response response = client.newCall(request).execute();
if (!response.isSuccessful()) throw new IOException("Unexpected code " + response);
System.out.println(response.body().string());
}
Example 4 : การส่งค่าไปกับ Header
private final OkHttpClient client = new OkHttpClient();
public void run() throws Exception {
Request request = new Request.Builder()
.url("https://api.github.com/repos/square/okhttp/issues")
.header("User-Agent", "OkHttp Headers.java")
.addHeader("Accept", "application/json; q=0.5")
.addHeader("Accept", "application/vnd.github.v3+json")
.build();
Response response = client.newCall(request).execute();
if (!response.isSuccessful()) throw new IOException("Unexpected code " + response);
System.out.println("Server: " + response.header("Server"));
System.out.println("Date: " + response.header("Date"));
System.out.println("Vary: " + response.headers("Vary"));
}
Example 5 : การส่งค่า Post แบบ JSON (Gson)
private final OkHttpClient client = new OkHttpClient();
private final Gson gson = new Gson();
public void run() throws Exception {
Request request = new Request.Builder()
.url("https://api.github.com/gists/c2a7c39532239ff261be")
.build();
Response response = client.newCall(request).execute();
if (!response.isSuccessful()) throw new IOException("Unexpected code " + response);
Gist gist = gson.fromJson(response.body().charStream(), Gist.class);
for (Map.Entry<String, GistFile> entry : gist.files.entrySet()) {
System.out.println(entry.getKey());
System.out.println(entry.getValue().content);
}
}
static class Gist {
Map<String, GistFile> files;
}
static class GistFile {
String content;
}
ตัวอย่างการใช้งานต่าง ๆ
.
|
ช่วยกันสนับสนุนรักษาเว็บไซต์ความรู้แห่งนี้ไว้ด้วยการสนับสนุน Source Code 2.0 ของทีมงานไทยครีเอท
|
|
|
By : |
ThaiCreate.Com Team (บทความเป็นลิขสิทธิ์ของเว็บไทยครีเอทห้ามนำเผยแพร่ ณ เว็บไซต์อื่น ๆ) |
|
Score Rating : |
![](/images/resource/startrue.gif) ![](/images/resource/startrue.gif) ![](/images/resource/startrue.gif) |
|
|
Create/Update Date : |
2015-11-22 13:02:58 /
2017-03-26 21:29:24 |
|
Download : |
No files |
|
Sponsored Links / Related |
|
|
|
|
|
|
|