• 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

  • 相关阅读:
    AngularJS学习之旅—AngularJS 服务(八)
    Svchost进程和共享服务病毒原理
    服务劫持
    利用BHO实现浏览器劫持
    动态反调试
    常用的静态反调试技术及其规避方法
    teb, peb,seh 结构
    线程本地存储tls
    注入技术总结
    注入技术--远程线程注入
  • 原文地址:https://www.cnblogs.com/begin1949/p/4927515.html
Copyright © 2020-2023  润新知