Android网络开发之OkHttp--基本用法POST

1、OkHttp框架使用了OkIo框架,不要忘记下OkIo.jar

2、通过POST访问网络,和通过GET访问网络基本相同,多了设置请求参数的过程。主要分为五步:

    (1)、声明并实例化一个OkHttpClient对象

    (2)、声明并实例化一个RequestBody对象

    (3)、声明并实例化一个Request对象

    (4)、执行Request请求,并得到一个Response对象

    (5)、根据Response的isSuccessful()方法判断是否成功,然后从Response对象中获取返回数据。

3、

public class PostActivity extends Activity {
    private OkHttpClient client = new OkHttpClient();
    
    private TextView mTvPost;
    
    private String url = "https://www.baidu.com/";
    
    private String result = "";

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        // TODO Auto-generated method stub
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_post);
        
        initView();
        
        new Thread(postThread).start();
    }
    
    public void initView(){
        mTvPost = (TextView) findViewById(R.id.tv_post_show);
    }
    
    private Handler postHandler = new Handler(){
        public void handleMessage(android.os.Message msg) {
            mTvPost.setText(result);
        };
    };
    
    private Thread postThread = new Thread(){
        public void run() {
            try {
                run();
            } catch (Exception e) {
                // TODO Auto-generated catch block
                e.printStackTrace();
            }
            
            postHandler.sendEmptyMessage(0);
        };
    };

    /** Posting a String */
    public static final MediaType jsonReq = MediaType.parse("application/json;charset=utf-8");

    public void run() throws IOException {
        RequestBody body = RequestBody.create(jsonReq, "{\"name\", \"name\"}");
        Request request = new Request.Builder().url(url).post(body).build();
        Response response = client.newCall(request).execute();
        result += response.body().string();
    }

    /** Posting a File */
    public static final MediaType MEDIA_TYPE_MARKDOWN1 = MediaType.parse("text/x-markdown;charset=utf-8");

    public void run2() throws Exception {
        File file = new File(Environment.getExternalStorageDirectory().getPath() + "/DCIM/Camera/IMG_20151030_205855.jpg");
        Request request = new Request.Builder().url(url).post(RequestBody.create(MEDIA_TYPE_MARKDOWN, file)).build();
        Response response = client.newCall(request).execute();
        if (!response.isSuccessful()){
            result += "出错" + response;
        }else{
            result += "没有出错" +response.body().string();
        }
    }

    /** Posting from parameters */
    public void run3() throws Exception {
        RequestBody formBody = new FormEncodingBuilder().add("search","Jurassic Park").build();
        Request request = new Request.Builder().url(url).post(formBody).build();
        Response response = client.newCall(request).execute();
        
        if (!response.isSuccessful()){
            result += "出错了";
        }else{
            result += response.body().toString();
        }
    }

    /** Posing Json with Gson */
    private final Gson gson = new Gson();

    public void run5() throws Exception {
        Request request = new Request.Builder().url(url).build();
        Response response = client.newCall(request).execute();
        if (!response.isSuccessful()){
            result += "出错了";
        }else{
            Gist gist = gson.fromJson(response.body().charStream(), Gist.class);
            for (Map.Entry<String, GistFile> entry : gist.files.entrySet()) {
                result += entry.getKey() + entry.getValue().content;
            }
        }
    }

    static class Gist {
        Map<String, GistFile> files;
    }

    static class GistFile {
        String content;
    }

}

4、访问网络不能在主线程中进行,还有不要忘记加入访问网络的权限。

<uses-permission android:name="android.permission.INTERNET" />

5、对于Request对象是如何实例化的,大家可以参考--java builder模式

http://www.cnblogs.com/moonz-wu/archive/2011/01/11/1932473.html

6、参考博文:

http://www.2cto.com/kf/201505/397557.html

 

posted on 2015-11-01 13:05  StephenHe  阅读(642)  评论(0编辑  收藏  举报

导航