OKHttp3用法介绍

OKHttp3用法介绍

我们把用http协议通讯的双方称作Client和Server,Client发送request请求,Server收到请求后处理并返回Client一个response.

接口简介

接口地址
http://10.4.44.24:8080/DemoApi/login?name=rico&pwd=123456

接口结构
- scheme:http
- ip: 10.4.44.24
- port: 8080
- path: /DemoApi/login
- query-string: name=rico&pwd=123456

接口错误码
- 200 OK // 客户端请求成功
- 400 Bad Request //客户端请求有语法错误
- 401 Unauthorised // 请求未经授权
- 403 Forbidden // 服务器收到请求,但拒绝服务
- 500 Internal Server Error // 服务器发生不可预期错误
- 503 Server unavailable // 服务器当前不能处理请求,一段时间后可能恢复正常


基本用法

一、Get请求(获取用户信息)

通过获取用户信息的例子来了解okhttp的基本用法,假设点击页面的Get按钮,来获取用户的头像和昵称。

public class MainActivity extends AppCompatActivity {

  TextView tvName;
  ImageView ivPortrait;

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

    tvName = (TextView) findViewById(R.id.name);
    ivPortrait = (ImageView) findViewById(R.id.portrait);
  }

  public void getUserInfo(View view) {
    Request request =
        new Request.Builder().url("http://10.4.44.24:8080/DemoApi/userInfo").get().build();
    OkHttpClient okHttpClient = new OkHttpClient();
    okHttpClient.newCall(request).enqueue(new Callback() {
      @Override public void onFailure(Call call, IOException e) {
      }

      @Override public void onResponse(Call call, Response response) throws IOException {
        if (response.code() != 200) return;
        try {
          String s = response.body().string();
          final UserInfo info = new Gson().fromJson(s, UserInfo.class);

          runOnUiThread(new Runnable() {
            @Override public void run() {
              tvName.setText(info.getUserName());
              Picasso.with(MainActivity.this)
                  .load(Uri.parse(info.getUserIconUrl()))
                  .into(ivPortrait);
            }
          });
        } catch (Exception e) {
          e.printStackTrace();
        }
      }
    });
  }
}

Gson和Picasso用于json解析和图片的显示,需要配置依赖:

compile 'com.google.code.gson:gson:2.8.0'
compile 'com.squareup.picasso:picasso:2.5.2'

点击Get按钮,获取头像和昵称如下:
这里写图片描述


二、Post请求(form表单形式)

用户登录,参数通过form表单形式传给服务器,示例如下:

public class LoginActivity extends AppCompatActivity {

  EditText etUserName;
  EditText etUserPwd;

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

    etUserName = (EditText) findViewById(R.id.et_name);
    etUserPwd = (EditText) findViewById(R.id.et_pwd);
  }


  public void login(View view) {
    String userName = etUserName.getText().toString().trim();
    String userPwd = etUserPwd.getText().toString().trim();

    RequestBody body = new FormBody.Builder()
        .add("user_name", userName)
        .add("user_pwd", userPwd)
        .build();
    Request request = new Request.Builder()
        .post(body)
        .url("http://10.4.33.125:8080/DemoApi/login")
        .build();
    new OkHttpClient().newCall(request)
        .enqueue(new Callback() {
          @Override public void onFailure(Call call, IOException e) {
          }

          @Override public void onResponse(Call call, Response response) throws IOException {
            System.out.println("login result:"+response.body().string());
          }
        });
  }
}

三、Post请求(json参数形式)

  public void login(View view) {
    String userName = etUserName.getText().toString().trim();
    String userPwd = etUserPwd.getText().toString().trim();

    String jsonParams = "";
    try {
      JSONObject jsonObject = new JSONObject();
      jsonObject.put("user_name", userName);
      jsonObject.put("user_pwd", userPwd);
      jsonParams = jsonObject.toString();
    } catch (Exception e) {
      e.printStackTrace();
    }

    RequestBody body = RequestBody.create(MediaType.parse("application/json"), jsonParams);
    Request request = new Request.Builder()
        .post(body)
        .url("http://10.4.33.125:8080/DemoApi/login")
        .build();
    new OkHttpClient().newCall(request)
        .enqueue(new Callback() {
          @Override public void onFailure(Call call, IOException e) {
          }

          @Override public void onResponse(Call call, Response response) throws IOException {
            System.out.println("login result:"+response.body().string());
          }
        });
  }
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

chengyuan9160

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值