OkHttp框架的簡單使用

佈局部分

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout
    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"
    android:orientation="vertical"
    android:paddingBottom="@dimen/activity_vertical_margin"
    android:paddingLeft="@dimen/activity_horizontal_margin"
    android:paddingRight="@dimen/activity_horizontal_margin"
    android:paddingTop="@dimen/activity_vertical_margin"
    tools:context="com.lt.okhttppost.MainActivity">

 <Button
     android:layout_width="match_parent"
     android:layout_height="wrap_content"
     android:onClick="StringClick"
     android:text="點我上傳String類型"/>

 <Button
     android:layout_width="match_parent"
     android:layout_height="wrap_content"
     android:onClick="KeyValueClick"
     android:text="點我上傳KeyValue類型"/>

 <Button
     android:layout_width="match_parent"
     android:layout_height="wrap_content"
     android:onClick="FileClick"
     android:text="點我上傳File類型"/>
</LinearLayout>

mainactivity 部分

package com.lt.okhttppost;

import android.os.Environment;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.util.Log;
import android.view.View;

import java.io.File;
import java.io.IOException;

import okhttp3.FormBody;
import okhttp3.MediaType;
import okhttp3.OkHttpClient;
import okhttp3.Request;
import okhttp3.RequestBody;
import okhttp3.Response;
import okhttp3.ResponseBody;

public class MainActivity extends AppCompatActivity {

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
    }

    //構建json字符串
    private String buildJson(String player1, String player2) {
        return "{'winCondition':'HIGH_SCORE',"
                + "'name':'Bowling',"
                + "'round':4,"
                + "'lastSaved':1367702411696,"
                + "'dateStarted':1367702378785,"
                + "'players':["
                + "{'name':'" + player1 + "','history':[10,8,6,7,8],'color':-13388315,'total':39},"
                + "{'name':'" + player2 + "','history':[6,10,5,10,10],'color':-48060,'total':41}"
                + "]}";
    }

    //
    public void StringClick(View view) {
        try {
//1.
            OkHttpClient okHttpClient = new OkHttpClient();
            //5.type  &  json
            MediaType type = MediaType.parse("application/json;charset=utf-8");
            String json = buildJson("Colin", "CHEN");
            //4.生成一個requestBody對象
            RequestBody requestBody = RequestBody.create(type, json);
            //3.
            Request request = new Request.Builder().url("需要我們上傳的地址【服務器的地址】").post(requestBody).build();
            //2.
            Response response = okHttpClient.newCall(request).execute();
            if (response.isSuccessful()){
                ResponseBody responseBody = response.body();
                String result = responseBody.string();
                Log.e("TAG","上傳成功"+result);
            }
        } catch (IOException e) {
            e.printStackTrace();
        }


    }

    //
    public void KeyValueClick(View view) {
      new Thread(new Runnable() {
          @Override
          public void run() {
              OkHttpClient okHttpClient = new OkHttpClient();
              try {
                  RequestBody body = new FormBody.Builder().add("_name","CHEN").add("_id","123").build();
                  Request request = new Request.Builder().url("").post(body).build();
                  Response response = okHttpClient.newCall(request).execute();
                  if (response.isSuccessful()){
                      String string = response.body().string();
                      Log.e("Tag","上傳成功"+string);
                  }
              } catch (IOException e) {
                  e.printStackTrace();
              }
          }
      }).start();
    }

    //
    public void FileClick(View view) {
        OkHttpClient okHttpClient = new OkHttpClient();
        try {
            MediaType type = MediaType.parse("text/*");
            String path = Environment.getExternalStorageDirectory().getAbsolutePath()+File.separator+"文件夾名"+File.separator + "文件名";
            File file = new File(path);
            RequestBody body = RequestBody.create(type,file);
            Request request = new Request.Builder().url("").post(body).build();
            Response response = okHttpClient.newCall(request).execute();
            if (response.isSuccessful()){
                String string = response.body().string();
                Log.e("TAG", "成功了---" + string);
            }

        } catch (IOException e) {
            e.printStackTrace();
        }
    }
}

Constants

package com.lt.okhttppost;

/**
 * Created by Administrator
 */
public class Constant {
    // 最新
    public final static String URL_LATEST0 = "http://lib.wap.zol.com.cn/ipj/docList.php?class_id=0&page=%d&vs=and380&retina=1";
    public final static String URL_LATEST = "http://m2.qiushibaike.com/article/list/latest?page=%d";

}
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章