OKHttp3用法介绍

来源:互联网 发布:gta5网络优化 编辑:程序博客网 时间:2024/06/07 13:28

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
原创粉丝点击