[Java]Http类库OkHttp使用举例(POST/GET/FormData/JSON/XML/File Multipart/超时)

2021-03-09 2566点热度 0人点赞 1条评论

前言

用Java来请求网络操作的使用,原生可以使用HttpURLConnection,但是原生的功能比较弱,这里推荐一个第三方的类库:OkHttp,它能将网络操作变得异常简单。

这里介绍下常见的Http操作,例如POST(FormData, JSON,XML,File)GET(普通,代理)等等

引入OKHttp依赖

如果是Maven,加入pom.xml:

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

如果是Gradle,加入build.gradle

implementation("com.squareup.okhttp3:okhttp:4.9.0")

GET

OkHttpClient client = new OkHttpClient().newBuilder().build();
Request request = new Request.Builder().url("https://httpbin.org/get").build();
Response response = client.newCall(request).execute();

//response.body()还可以返回InputStream byteStream(),或者返回bytes[],但是注意可能body()会返回null
System.out.println(response.body().string());
//返回状态代码 200 等
System.out.println(response.code());

//或者使用try with resource的方式 
//try (Response response = client.newCall(request).execute()) {
//    System.out.println(response.body().string()); 
//}

使用代理的方式GET

java.net.Proxy proxy = new Proxy(Proxy.Type.SOCKS, new java.net.InetSocketAddress("127.0.0.1", 1080));
OkHttpClient client = new OkHttpClient().newBuilder().proxy(proxy).build();
Request request = new Request.Builder().url("http://ip-api.com/csv?fields=status,isp,query,country,city").build();
Response response = client.newCall(request).execute();
response.body();

POST Form Data 表单提交

OkHttpClient client = new OkHttpClient().newBuilder().build();
FormBody formBody = new FormBody.Builder()
        .add("xxx", "xxx")
        .add("message", message)
        .build();
Request request = new Request.Builder().url("https://www.example.com").post(formBody).build();
Response response = client.newCall(request).execute();
System.out.println(response.body().string());

POST JSON

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

public static void main(String[] args) throws Exception {
    String payload = "{\"no\": \"admin\", \"username\": \"Terry\"}";
    RequestBody body = RequestBody.create(JSON, payload);
    Request request = new Request.Builder()
            .url("http://example.com/post_url")
            .addHeader("Content-Type", "application/json; charset=utf-8")
            .post(body)
            .build();

    OkHttpClient client = new OkHttpClient().newBuilder().build();
    Response response = client.newCall(request).execute();
    response.body();

}

POST XML

这个只要把上面JSON的例子的Content-Type改成application/xml; charset=UTF-8,内容(Body)放XML就可以了。

POST File Multipart 上传文件

OkHttpClient client = new OkHttpClient().newBuilder().build();

File file = new File("/path/to/file.xlsx");

RequestBody requestBody = new MultipartBody.Builder()
        .setType(MultipartBody.FORM)
        .addFormDataPart("title", "销售表")
        .addFormDataPart("other_parameter", "other_parameter_value")
        .addFormDataPart("file", file.getName(),
                RequestBody.create(file, MediaType.parse("application/octet-stream")))
        .build();

// RequestBody.create(file,MediaType.parse("application/")); 的file也可以替换成byte[] 直接是data数组

Request request = new Request.Builder().url("https://www.example.com/post_file_url").post(requestBody).build();

Response response = client.newCall(request).execute();
response.body();

其他Methond(PUT,Delete)

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

String payload = "{\"no\": \"admin\", \"username\": \"Terry\"}";
RequestBody body =  RequestBody.create(JSON, payload);
OkHttpClient client = new OkHttpClient();
// DELETE or PUT
Request request = new Request.Builder().url(url).method("DELETE", body).build();
//or 
Request request = new Request.Builder().url("url").delete(body).build();
Response response = client.newCall(request).execute();

设置超时

OkHttpClient client = new OkHttpClient().newBuilder()
                    .connectTimeout(60, TimeUnit.SECONDS) //连接超时 60秒
                    .readTimeout(60, TimeUnit.SECONDS) //读取超时 60秒
                    .writeTimeout(60, TimeUnit.SECONDS) //写超时 60秒
                    .build();

 

 

 

admin

这个人很懒,什么都没留下

文章评论

  • vissitato

    Cialis Theyre not well understood which can make it difficult for doctors to know how to treat them this can be frustrating for men who have them. Rodmvn Yxmboi Possible Complications Complications occur as a result of associated conditions rather than as a result of acrodermatitis. cialis online generic Rdiyxr

    2022-04-10
  • 您需要 登录 之后才可以评论