(Rest API)OkHttp
首先先在gradle裡面加入:
compile 'com.squareup.okhttp:okhttp:2.4.0'
compile 'com.squareup.okio:okio:1.4.0'
接著在AndroidManifest裡面加入下面兩段來獲取網路連線資源
<uses-permission android:name="android.permission.INTERNET" />
<uses-permission android:name="android.permission.ACCESS_NETWORK_STATE" />
GET
Request request = new Request.Builder()
.url(url)
.build();
POST
RequestBody formBody = new FormEncodingBuilder()
.add("name", userName)
.add("pass", passWord)
.build();
Request request = new Request.Builder()
.url(params[0]).post(formBody)
.build();
SEND
try {
Response response=client.newCall(request).execute();
if (!response.isSuccessful())
throw new IOException("Unexpected code " + response.toString());
return response.body().string();
} catch (IOException e) {
e.printStackTrace();
}
Http攜帶參數
RequestBody forBody=new FormEncodingBuilder()
.add("name",UserName)
.add("pass",UserPass)
.build();
Request request=new Request.Builder()
.url(params[0]).post(forBody)
.build();
下方實做圖片下載
在Layout的地方只需要加入一個按鈕跟一個ImageView就可以了
<ImageView
android:id="@+id/imageView1"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:layout_centerHorizontal="true"
android:layout_centerVertical="true"
android:visibility="invisible"
android:src="@drawable/ic_launcher" />
<Button
android:id="@+id/button1"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_centerHorizontal="true"
android:layout_centerVertical="true"
android:text="Download Image" />
建立一個Class去繼承AsyncTesk之後實作OkHttpClient
public class OkHttpHandler extends AsyncTask<String, Void, byte[]> {
OkHttpClient client = new OkHttpClient();
@Override
protected byte[] doInBackground(String... params) {
Request.Builder builder = new Request.Builder();
builder.url(params[0]);
Request request = builder.build();
try {
Response response = client.newCall(request).execute();
return response.body().bytes();
} catch (Exception e) {
}
return null;
最後在Main裡面去實體化剛建立的Class
dowloadBtn.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
// TODO Auto-generated method stub
dowloadBtn.setVisibility(View.INVISIBLE);
OkHttpHandler handler = new OkHttpHandler();
byte[] image = new byte[0];
try {
image = handler.execute(URL).get();
if (image != null && image.length > 0) {
Bitmap bitmap = BitmapFactory.decodeByteArray(image, 0,
image.length);
mImage.setImageBitmap(bitmap);
mImage.setVisibility(View.VISIBLE);
就完成了!