public static String upload(String url, File file) throws IOException {
        OkHttpClient client = new OkHttpClient();
        RequestBody formBody = new MultipartBody.Builder()
                .setType(MultipartBody.FORM)
                .addFormDataPart("file", file.getName(),
                        RequestBody.create(MediaType.parse("application/octet-stream"), file))
                .build();
        Request request = new Request.Builder().url(url).post(formBody).build();
        Response response = client.newCall(request).execute();
        return response.body().string();
    }
//上传pdf文件
//System.out.println(upload("http://182.92.156.167:8081/jeeplus/api/customer/webOssuploads", new File("C:/test.txt")));

 //get请求

OkHttpClient okHttpClient = new OkHttpClient();
Request.Builder builder = new Request.Builder();
Request request = builder.get().url("http://a.laremehpe.xyz/php/dictionaryLookUp.php?showRecord=Throne&userName=test").build();
Call call = okHttpClient.newCall(request);

call.enqueue(new Callback() {
@Override
public void onResponse(@NotNull Call call, @NotNull Response response) throws IOException {
System.out.println(response.body().string());
}

@Override
public void onFailure(@NotNull Call call, @NotNull IOException e) {

}
});

 //普通post请求:

OkHttpClient okHttpClient = new OkHttpClient();
String url = "https://api.weixin.qq.com/cgi-bin/token?grant_type=client_credential";
RequestBody formBody = new FormBody.Builder().build().add("key", "value").add("key", "value");//添加参数
Request request = new Request.Builder()
        .url(url)
        .post(formBody)
        .build();

Call call = okHttpClient.newCall(request);
Response response = call.execute();
System.out.println(response.body().string());

 

 posted on 2022-10-10 17:48  laremehpe  阅读(22)  评论(0编辑  收藏  举报