Register Register Member Login Member Login Member Login Forgot Password ??
PHP , ASP , ASP.NET, VB.NET, C#, Java , jQuery , Android , iOS , Windows Phone



Clound SSD Virtual Server

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

การติดตั้งสามารถดาวน์โหลดไฟล์ .JAR แล้วนำไป Import ลงใน Eclipse หรือ Android Studio

Android and Glide

ในการใช้งาน 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

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>









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



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








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;
  }


ตัวอย่างการใช้งานต่าง ๆ



.

   
Share


ช่วยกันสนับสนุนรักษาเว็บไซต์ความรู้แห่งนี้ไว้ด้วยการสนับสนุน Source Code 2.0 ของทีมงานไทยครีเอท


ลองใช้ค้นหาข้อมูล


   


Bookmark.   
       
  By : ThaiCreate.Com Team (บทความเป็นลิขสิทธิ์ของเว็บไทยครีเอทห้ามนำเผยแพร่ ณ เว็บไซต์อื่น ๆ)
  Score Rating :  
  Create/Update Date : 2015-11-22 13:02:58 / 2017-03-26 21:29:24
  Download : No files
 Sponsored Links / Related

 
Android and Ion (HTTP LIB:Library)
Rating :

 
Android and Asynchronous Http Client - com.loopj : (HTTP LIB:Library)
Rating :


ThaiCreate.Com Forum


Comunity Forum Free Web Script
Jobs Freelance Free Uploads
Free Web Hosting Free Tools

สอน PHP ผ่าน Youtube ฟรี
สอน Android การเขียนโปรแกรม Android
สอน Windows Phone การเขียนโปรแกรม Windows Phone 7 และ 8
สอน iOS การเขียนโปรแกรม iPhone, iPad
สอน Java การเขียนโปรแกรม ภาษา Java
สอน Java GUI การเขียนโปรแกรม ภาษา Java GUI
สอน JSP การเขียนโปรแกรม ภาษา Java
สอน jQuery การเขียนโปรแกรม ภาษา jQuery
สอน .Net การเขียนโปรแกรม ภาษา .Net
Free Tutorial
สอน Google Maps Api
สอน Windows Service
สอน Entity Framework
สอน Android
สอน Java เขียน Java
Java GUI Swing
สอน JSP (Web App)
iOS (iPhone,iPad)
Windows Phone
Windows Azure
Windows Store
Laravel Framework
Yii PHP Framework
สอน jQuery
สอน jQuery กับ Ajax
สอน PHP OOP (Vdo)
Ajax Tutorials
SQL Tutorials
สอน SQL (Part 2)
JavaScript Tutorial
Javascript Tips
VBScript Tutorial
VBScript Validation
Microsoft Access
MySQL Tutorials
-- Stored Procedure
MariaDB Database
SQL Server Tutorial
SQL Server 2005
SQL Server 2008
SQL Server 2012
-- Stored Procedure
Oracle Database
-- Stored Procedure
SVN (Subversion)
แนวทางการทำ SEO
ปรับแต่งเว็บให้โหลดเร็ว


Hit Link
   







Load balance : Server 01
ThaiCreate.Com Logo
© www.ThaiCreate.Com. 2003-2024 All Rights Reserved.
ไทยครีเอทบริการ จัดทำดูแลแก้ไข Web Application ทุกรูปแบบ (PHP, .Net Application, VB.Net, C#)
[Conditions Privacy Statement] ติดต่อโฆษณา 081-987-6107 อัตราราคา คลิกที่นี่