Square. Github. IO/OkHttp /. This article demonstrated common operations such as simple Get, Post (form and JSON), Delete, attaching request headers, request asynchronous callbacks, and file uploads and downloads using the OkHttp framework.

Square. Github. IO/OkHttp /. This article demonstrated common operations such as simple Get, Post (form and JSON), Delete, attaching request headers, request asynchronous callbacks, and file uploads and downloads using the OkHttp framework. Response.body ().string() can only be called once. Note the change caused to the result when debugging! There are many changes to HttpURLConnection in JDK9, which will be demonstrated and explained in the next blog post.

The preferred way to import this dependency is to use OkHTTP

< the dependency > < groupId > com. Squareup. Okhttp3 < / groupId > < artifactId > okhttp < / artifactId > < version > 3.6.0 < / version > </dependency> <! <dependency> <groupId>com.alibaba</groupId> <artifactId>fastjson</artifactId> The < version > 1.2.47 < / version > < / dependency >Copy the code

If the project is managed by Gradle, you only need to introduce:

The compile 'com. Squareup. Okhttp3: okhttp: 3.6.0'Copy the code

1. Get request example

String url = "http://zouchanglin.cn";
OkHttpClient okHttpClient = new OkHttpClient();
Request request = new Request.Builder().get().url(url).build();
try {
    Response execute = okHttpClient.newCall(request).execute();
    System.out.println(execute.body().string());
} catch (IOException e) {
    e.printStackTrace();
}
Copy the code

2. Post request example

1. JSON request

public static void main(String[] args) { String url = "http://zouchanglin.cn/info/create"; OkHttpClient okHttpClient = new OkHttpClient(); Map<String, Object> map = new HashMap<>(); map.put("name", "Mike"); map.put("age", "20"); RequestBody requestBody = RequestBody.create( MediaType.parse("application/json; charset=utf-8"), JSONObject.toJSONString(map)); Request request = new Request.Builder().post(requestBody).url(url).build(); try { Response response = okHttpClient.newCall(request).execute(); System.out.println(response.body().string()); } catch (IOException e) { e.printStackTrace(); }}Copy the code

2. Form data

public static void main(String[] args) { String url = "http://zouchanglin.cn/info/create"; OkHttpClient okHttpClient = new OkHttpClient(); RequestBody requestBody = new FormBody.Builder() .add("name", "Mike") .add("age", "20").build(); Request request = new Request.Builder().post(requestBody).url(url).build(); try { Response response = okHttpClient.newCall(request).execute(); System.out.println(response.body().string()); } catch (IOException e) { e.printStackTrace(); }}Copy the code

3. Delete request example

public static void main(String[] args) { String url = "http://zouchanglin.cn/info/remove"; OkHttpClient okHttpClient = new OkHttpClient(); RequestBody requestBody = new FormBody.Builder() .add("id", "001002003004").build(); Request request = new Request.Builder() .delete(requestBody).url(url).build(); try { Response response = okHttpClient.newCall(request).execute(); System.out.println(response.body().string()); } catch (IOException e) { e.printStackTrace(); }}Copy the code

4. Examples of additional requests

public static void main(String[] args) {
    String url = "http://zouchanglin.cn/info/remove";
    OkHttpClient okHttpClient = new OkHttpClient();
    RequestBody requestBody = new FormBody.Builder()
        .add("id", "001002003004").build();
    Request request = new Request.Builder()
        .delete(requestBody)
        .addHeader("Accept", "application/vnd..")
        .url(url).build();
    try {
        Response response = okHttpClient.newCall(request).execute();
        System.out.println(response.body().string());
    } catch (IOException e) {
        e.printStackTrace();
    }
}
Copy the code

5. Request asynchronous callback example

public static void main(String[] args) { String url = "http://zouchanglin.cn/info/remove"; OkHttpClient okHttpClient = new OkHttpClient(); RequestBody requestBody = new FormBody.Builder() .add("id", "0010003004").build(); Request request = new Request.Builder().delete(requestBody).url(url).build(); Call call = okHttpClient.newCall(request); call.enqueue(new Callback() { @Override public void onFailure(Call call, IOException e) { //TODO... } @Override public void onResponse(Call call, Response response) throws IOException { //TODO... }}); }Copy the code

6. Example of uploading file parameters

@PostMapping("upload") public String uploadToRemoteHost(String ip, String path, String fileId) { String url = String.format("http://%s:8080//api/host/file/create/", ip); / / find the file object Optional < ImageFile > bigFileById = fileService. GetBigFileById (count); if(bigFileById.isPresent()){ ImageFile imageFile = bigFileById.get(); OkHttpClient okHttpClient = new OkHttpClient(); MultipartBody.Builder requestBody = new MultipartBody.Builder(); requestBody.setType(MultipartBody.FORM); RequestBody body = RequestBody.create( MediaType.parse("application/octet-stream"), imageFile.getContent().getData()); / / parameters respectively request key file name RequestBody RequestBody. AddFormDataPart (" file ", imageFile getName (), the body). // Text parameters to upload Map<String, String> Map = new HashMap<>(); map.put("name", imageFile.getName()); map.put("path", path); for (String key : map.keySet()) { requestBody.addFormDataPart(key, map.get(key)); } MultipartBody build = requestBody.build(); try { Request request = new Request.Builder().post(build).url(url).build(); Response execute = okHttpClient.newCall(request).execute(); if(execute.isSuccessful()){ return execute.body().string(); } return jsonObject.tojsonString (resultvoutil. error(1, "network error ")); } catch (IOException e) { e.printStackTrace(); Return jsonObject.tojsonString (resultvoutil. error(2, "network error 2")); }} return jsonObject.tojsonString (resultvoutil. error(3, "file does not exist ")); }Copy the code

7. Download file examples

public void downloadImg(View view){ OkHttpClient client = new OkHttpClient(); final Request request = new Request.Builder().get() .url("http://wwwx.yyy/a.png") .build(); Call call = client.newCall(request); call.enqueue(new Callback() { @Override public void onFailure(Call call, IOException e) { Log.e("moer", "onFailure: ");; } @Override public void onResponse(Call call, Throws IOException {InputStream is = response.body().byteStream(); int len = 0; File file = new File(Environment.getExternalStorageDirectory(), "n.png"); FileOutputStream fos = new FileOutputStream(file); byte[] buf = new byte[128]; while ((len = is.read(buf)) ! = -1){ fos.write(buf, 0, len); } fos.flush(); Fos. Close (); is.close(); }}); }Copy the code

8. OkHttp pit

The OkHttp request callback response.body().string() can only be effectively called once. The data flow is closed when response.body().string() is called. Throw a Java. Lang. An IllegalStateException: Closed exception, so this hole is still a bit big. I have already monitored the return value of Response.body ().string() for a time when I debug, and it is IllegalStateException when I run it out in the code. Debugging code When debugging, expression monitoring can sometimes affect how the code works, as in the case of OkHttp.