OkHttp3的使用

本文详细介绍了如何在Android应用中使用OkHttp3库进行GET和POST请求。包括库的导入、GET请求的同步与异步实现、POST请求的参数传递方式,以及不同Content-Type的RequestBody创建方法。

OkHttp3的使用

Android Studio的导入

compile 'com.squareup.okhttp3:okhttp:3.2.0'
compile 'com.squareup.okio:okio:1.6.0'

 

1、GET请求

String url = "https://www.baidu.com/";
OkHttpClient okHttpClient = new OkHttpClient();
Request request = new Request.Builder()
    .url(url)
    .build();
Call call = okHttpClient.newCall(request);
try {
    Response response = call.execute();
    System.out.println(response.body().string());
} catch (IOException e) {
    e.printStackTrace();

}

Response response = call.execute();这个是同步的

回调也可用

call.enqueue(new Callback() {
    @Override
    public void onFailure(Call call, IOException e) {
        button.setText("false");
    }

    @Override
    public void onResponse(Call call, Response response) throws IOException {
        Message msg = Message.obtain();
        msg.obj = response.body().string();
        msg.what = 111;
        handler.sendMessage(msg);
        runOnUiThread(new Runnable() {
            @Override
            public void run() {
                button.setText("true");
            }
        });

    }
});

只不过这个是异步的,可以调用runOnUiThread()去UI线程操作

 

2、POST请求

RequestBody body = new FormBody.Builder()
    .add("键", "值")
    .add("键", "值")
    ...
    .build();

Request request = new Request.Builder()
    .url(url)
    .post(body)

    .build();

用一个RequestBody去传参数

post请求创建request和get是一样的,只是post请求需要提交一个表单,就是RequestBody。表单的格式有好多种,普通的表单是:

RequestBody body = new FormBody.Builder()
    .add("键", "值")
    .add("键", "值")
    ...
    .build();

RequestBody的数据格式都要指定Content-Type,常见的有三种:

  • application/x-www-form-urlencoded 数据是个普通表单
  • multipart/form-data 数据里有文件
  • application/json 数据是个json

 

但是好像以上的普通表单并没有指定Content-Type,这是因为FormBody继承了RequestBody,它已经指定了数据类型为application/x-www-form-urlencoded。

private static final MediaType CONTENT_TYPE = MediaType.parse("application/x-www-form-urlencoded");

再看看数据为其它类型的RequestBody的创建方式。

如果表单是个json:

MediaType JSON = MediaType.parse("application/json; charset=utf-8");
RequestBody body = RequestBody.create(JSON, "你的json");

如果数据包含文件:

RequestBody requestBody = new MultipartBody.Builder()
    .setType(MultipartBody.FORM)
    .addFormDataPart("file", file.getName(), RequestBody.create(MediaType.parse("image/png"), file))
    .build();

上面的MultipartBody也是继承了RequestBody,看下源码可知它适用于这五种Content-Type:

public static final MediaType MIXED = MediaType.parse("multipart/mixed");
public static final MediaType ALTERNATIVE = MediaType.parse("multipart/alternative");
public static final MediaType DIGEST = MediaType.parse("multipart/digest");
public static final MediaType PARALLEL = MediaType.parse("multipart/parallel");
public static final MediaType FORM = MediaType.parse("multipart/form-data");

另外如果你上传一个文件不是一张图片,但是MediaType.parse("image/png")里的"image/png"不知道该填什么,可以参考下这个页面

 

 

### OkHttp3 GET 和 POST 请求的使用方法 #### 发起 GET 请求 通过 `OkHttpClient` 实现 GET 请求非常简单。下面展示了一个完整的 Java 示例代码: ```java import okhttp3.OkHttpClient; import okhttp3.Request; import okhttp3.Response; public class GetRequestExample { public static void main(String[] args) throws Exception { OkHttpClient client = new OkHttpClient(); Request request = new Request.Builder() .url("https://example.com/api?key=value") // 替换为实际 URL[^2] .build(); try (Response response = client.newCall(request).execute()) { if (!response.isSuccessful()) throw new IOException("Unexpected code " + response); System.out.println(response.body().string()); } } } ``` 上述代码展示了如何创建一个简单的 GET 请求并打印返回的结果。 --- #### 发起 JSON 参数的 POST 请求 对于需要传递 JSON 数据的情况,可以按照如下方式构建请求体并通过 POST 方法发送: ```java import okhttp3.MediaType; import okhttp3.OkHttpClient; import okhttp3.Request; import okhttp3.RequestBody; import okhttp3.Response; public class PostJsonRequestExample { public static final MediaType JSON = MediaType.get("application/json; charset=utf-8"); public static void main(String[] args) throws Exception { OkHttpClient client = new OkHttpClient(); String jsonBody = "{ \"username\": \"test\", \"password\": \"1234\" }"; // 自定义JSON字符串 RequestBody body = RequestBody.create(jsonBody, JSON); Request request = new Request.Builder() .url("https://example.com/api/login") // 替换为目标URL .post(body) .build(); try (Response response = client.newCall(request).execute()) { if (!response.isSuccessful()) throw new IOException("Unexpected code " + response); System.out.println(response.body().string()); } } } ``` 此代码片段演示了如何向服务器发送带有 JSON 数据的 POST 请求,并接收响应内容。 --- #### 提交 Form 表单的 POST 请求 如果目标 API 需要以表单形式提交数据,则可以通过以下方式进行操作: ```java import okhttp3.FormBody; import okhttp3.OkHttpClient; import okhttp3.Request; import okhttp3.Response; public class PostFormRequestExample { public static void main(String[] args) throws Exception { OkHttpClient client = new OkHttpClient(); FormBody formBody = new FormBody.Builder() .add("username", "test") .add("password", "1234") .build(); Request request = new Request.Builder() .url("https://example.com/api/form-submit") // 替换为目标URL .post(formBody) .build(); try (Response response = client.newCall(request).execute()) { if (!response.isSuccessful()) throw new IOException("Unexpected code " + response); System.out.println(response.body().string()); } } } ``` 这段代码说明了如何利用 `FormBody.Builder()` 构建键值对的形式来模拟 HTML 表单提交的过程[^1]。 --- ### 总结 以上分别介绍了基于 OkHttp3 的三种常见网络请求场景:GET 请求、带 JSON 参数的 POST 请求以及表单提交类型的 POST 请求。每种情况都提供了具体的实现细节和样例代码供参考。
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值