OkHttp POST请求Java示例

x33g5p2x  于4个月前 转载在 Java  
字(4.9k)|赞(0)|评价(0)|浏览(211)

在本文中,我们将用Java创建一个OkHttppost HTTP请求示例。

OkHTTP是一个开源项目,旨在成为Android和Java应用程序的高效HTTP客户端。

OkHttp支持Android 5.0+(API级别21+)和Java 1.8+。在本文中,我们将使用Java1.8+编写代码。

Maven依赖项

首先将库作为依赖项添加到pom.xml中:

<dependency>
    <groupId>com.squareup.okhttp3</groupId>
    <artifactId>okhttp</artifactId>
    <version>3.9.0</version>
</dependency>

要查看此库的最新依赖项,请查看page on Maven Central

OkHttp POST请求Java示例

在这个例子中,我们将为spring boot CRUD示例项目发出POST HTTP客户端请求。这个spring-boot-crud示例项目已经部署、启动并运行。

package com.javaguides.okhttp.tutorial.crud;

import java.io.IOException;
import okhttp3.MediaType;
import okhttp3.OkHttpClient;
import okhttp3.Request;
import okhttp3.RequestBody;
import okhttp3.Response;

public class OkHttpPost {

    public static final MediaType JSON = MediaType.parse("application/json; charset=utf-8");

    OkHttpClient client = new OkHttpClient();

    String post(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();
        }
    }

    public static void main(String[] args) throws IOException {
        OkHttpPost example = new OkHttpPost();
        String json = "{\r\n" +
            " \"firstName\" : \"Ramesh\",\r\n" +
            " \"lastName\" : \"Fadatare\",\r\n" +
            " \"emailId\" : \"ramesh@gmail.com\"\r\n" +
            "}";
        String response = example.post("http://localhost:8080/api/v1/employees", json);
        System.out.println(response);
    }
}

下图显示了源代码的屏幕截图以及输出:

基本POST请求示例

在这个简单的例子中,我们构建了一个RequestBody,用POST请求发送两个参数——“用户名”和“密码”:

package com.javaguides.okhttp.tutorial;

import java.io.IOException;

import okhttp3.Call;
import okhttp3.FormBody;
import okhttp3.OkHttpClient;
import okhttp3.Request;
import okhttp3.RequestBody;
import okhttp3.Response;

public class OkHttpPostRequestParameterExample {

    private static final String BASE_URL = "http://localhost:8080/spring-rest";

    static OkHttpClient client = new OkHttpClient();

    public static void main(String[] args) throws IOException {
        final RequestBody formBody = new FormBody.Builder()
            .add("username", "test")
            .add("password", "test").build();

        final Request request = new Request.Builder()
            .url(BASE_URL + "/users")
            .post(formBody).build();

        final Call call = client.newCall(request);
        final Response response = call.execute();
        System.out.println(response);
    }
}

POST请求和JSON示例

在本例中,我们将发送一个POST请求,其中JSON为RequestBody:

package com.javaguides.okhttp.tutorial;

import java.io.IOException;
import okhttp3.MediaType;
import okhttp3.OkHttpClient;
import okhttp3.Request;
import okhttp3.RequestBody;
import okhttp3.Response;

public class OkHttpPostExample {

    public static final MediaType JSON = MediaType.parse("application/json; charset=utf-8");

    OkHttpClient client = new OkHttpClient();

    String post(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();
        }
    }

    String bowlingJson(String player1, String player2) {
        return "{'winCondition':'HIGH_SCORE'," + "'name':'Bowling'," + "'round':4," + "'lastSaved':1367702411696," +
            "'dateStarted':1367702378785," + "'players':[" + "{'name':'" + player1 +
            "','history':[10,8,6,7,8],'color':-13388315,'total':39}," + "{'name':'" + player2 +
            "','history':[6,10,5,10,10],'color':-48060,'total':41}" + "]}";
    }

    public static void main(String[] args) throws IOException {
        OkHttpPostExample example = new OkHttpPostExample();
        String json = example.bowlingJson("Jesse", "Jake");
        String response = example.post("http://www.roundsapp.com/post", json);
        System.out.println(response);
    }
}

输出:

http://www.roundsapp.com/393141003

请注意,输出响应URL包含新创建的资源的ID。

Multipart POST请求

在这个例子中,我们将发送一个POST Multipart Request。我们需要将RequestBody构建为MultipartBody,以发布文件、用户名和密码:

package com.javaguides.okhttp.tutorial;

import java.io.File;
import java.io.IOException;

import okhttp3.Call;
import okhttp3.MediaType;
import okhttp3.MultipartBody;
import okhttp3.OkHttpClient;
import okhttp3.Request;
import okhttp3.RequestBody;
import okhttp3.Response;

public class OkHttpPostUploadFileExample {

    private static final String BASE_URL = "http://localhost:8080/spring-rest";

    static OkHttpClient client = new OkHttpClient();

    public static void main(String[] args) throws IOException {

        RequestBody requestBody = new MultipartBody.Builder().setType(MultipartBody.FORM)
            .addFormDataPart("username", "test").addFormDataPart("password", "test")
            .addFormDataPart("file", "file.txt", RequestBody.create(MediaType.parse("application/octet-stream"),
                new File("src/test/resources/test.txt")))
            .build();

        Request request = new Request.Builder().url(BASE_URL + "/users/multipart").post(requestBody).build();

        Call call = client.newCall(request);
        Response response = call.execute();
        System.out.println(response.code());
    }
}

相关文章

微信公众号

最新文章

更多