Kiba518

Kiba518

沈阳-架构-开发。

Fork me on GitHub

OKhttp3的使用教程

首先在build.gradle下的dependencies下添加引用。

implementation "com.squareup.okhttp3:okhttp:4.9.0"

然后编写HttpHelper的Get和Post方法。

public class HttpHelper {
    public static final OkHttpClient client = new OkHttpClient();
​
    public static void get(String url, ICallback_Comm callback) throws IOException {
       new Thread(){
           @Override
           public void run(){
               Request request = new Request.Builder()
                       .url(url)
                       .build();
​
               try (Response response = client.newCall(request).execute()) {
                    String result = response.body().string();
                    callback.Call(result);
               } catch (IOException | ClassNotFoundException e) {
                   e.printStackTrace();
               }
           }
       }.start();
​
    }
    //public static final MediaType JSON  = MediaType.get("application/json; charset=utf-8");
    public static final MediaType mediaType  = MediaType.get("application/octet-stream; charset=utf-8");
    public static void post(String url, String param, ICallback_Comm callback) throws IOException {
        new Thread(){
            @Override
            public void run(){
                RequestBody body = RequestBody.create(mediaType, param);
                Request request = new Request.Builder()
                        .url(url)
                        .post(body)
                        .build();
​
                try (Response response = client.newCall(request).execute()) {
                    String result = response.body().string();
                    callback.Call(result);
                } catch (IOException | ClassNotFoundException e) {
                    e.printStackTrace();
                }
            }
        }.start();
​
    } 
}

这里Post的MediaType设置成了application/octet-stream,因为我提交的数据是普通字符串,如果需要提交Json,则可设置为application/json。

使用HttpHelper模拟登陆。

Get:

 HttpHelper.get(AppConfig.WebApiCommUrl+"?para="+URLEncoder.encode("{\"LoginName\":\"admin\",\"Password\":\"admin\"}"),con->{ }); 

Post:

  HttpHelper.post(AppConfig.WebApiCommUrl,URLEncoder.encode("{\"LoginName\":\"admin\",\"Password\":\"admin\"}"),  con->{ 
                        LoginCommandResult baseResult =  JsonHelper.Deserialize(LoginCommandResult.class ,con);
                        if(baseResult.IsSuccess){
                        }
                        else {
                            runOnUiThread(()->{
                                ShowMessage("登录失败,"+baseResult.Message);
                            });
                        }
                        runOnUiThread(()->{
                            loginButton.setEnabled(true);
                            loadingProgressBar.setVisibility(View.GONE);
                        });
                    });

PS1:Android中不能在子线程中来刷新UI线程。可以使用runOnUiThread切换回UI线程,然后控制UI。

 runOnUiThread(()->{
       Toast.makeText(this, msg, Toast.LENGTH_SHORT).show();
 });

PS1:Alt+Insert会弹出自动生成菜单,选择Getter and Setter可以自动将字段生成属性,即生成get和set的属性函数。

PS3://region和//endregion组合可以折叠代码,类似C#的#region和#endregion。

PS4:获取集合长度,java里用size函数,比如If(list.size()>0),取第一个元素用get(index)方法,如list.get(0)。

----------------------------------------------------------------------------------------------------

注:此文章为原创,任何形式的转载都请联系作者获得授权并注明出处!
若您觉得这篇文章还不错,请点击下方的推荐】,非常感谢!

 

 

posted @ 2021-09-07 09:13  kiba518  阅读(1546)  评论(0编辑  收藏  举报