欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页

Android Okhttp 使用

程序员文章站 2022-04-14 09:29:11
...

1.基本使用

1.1 字符串读取

//这个程序下载一个URL并将其内容返回为字符串
OkHttpClient client = new OkHttpClient();

String getStringFromUrl(String url) throws IOException {
  Request request = new Request.Builder()
      .url(url)
      .build();

  try (Response response = client.newCall(request).execute()) {
    return response.body().string();
  }
}
// 该程序将数据发送到服务,json数据形式。
public static final MediaType JSON
    = MediaType.get("application/json; charset=utf-8");

OkHttpClient client = new OkHttpClient();

String postToServe(String url, String json) throws IOException {
  RequestBody body = RequestBody.create(json, JSON);
  Request request = new Request.Builder()
      .url(url)
      .post(body)
      .build();
  try (Response response = client.newCall(request).execute()) {
    return response.body().string();
  }
}

1.2 文件下载

例如:

Android Okhttp 使用

参考下面注解得到以上使用方法:

Android Okhttp 使用

以下是使用方式:

Response response = client.newCall(request).execute();
InputStream in = response.body().byteStream();
byte[] b = new byte[1024];
int len;
while ((len = in.read(b)) != -1) {
	// 写入文件(使用RandomAccessFile)
    file.write(b, 0, len);
}
response.body().close();

1.3 文件上传

摘抄自:https://www.jianshu.com/p/d176b35510c9

// 上传文件(没测试)
class ClientUploadUtils {

    static ResponseBody upload(String url, String filePath, String fileName) throws Exception {
        OkHttpClient client = new OkHttpClient()
        RequestBody requestBody = new MultipartBody.Builder()
                .setType(MultipartBody.FORM)
                .addFormDataPart("file", fileName,
                        RequestBody.create(MediaType.parse("multipart/form-data"), new File(filePath)))
                .build()

        Request request = new Request.Builder()
                .header("Authorization", "Client-ID " + UUID.randomUUID())
                .url(url)
                .post(requestBody)
                .build()

        Response response = client.newCall(request).execute();
        if (!response.isSuccessful()) throw new IOException("Unexpected code " + response)

        return response.body()
    }


    static void main(String[] args) throws IOException {
        try {
            String fileName = "com.jdsoft.biz.test.zip"
            String filePath = "D:\\ExtJsTools\\Sencha\\Cmd\\repo\\pkgs\\test.zip"
            String url = "http://localhost:9990/upload_app_package"
            System.out.println(upload(url, filePath, fileName).string())
        } catch (Exception e) {
            e.printStackTrace()
        }
    }

}

2. 参考

https://github.com/square/okhttp
https://www.jianshu.com/p/d176b35510c9