2020-05-05

原文地址

创建连接:

CloseableHttpClient httpClient = HttpClientBuilder.create().build();

String BASE_URL = "[http://www.xinfei.com](http://www.xinfei.com/)";

GET请求:

@Test

public void testGet() throws IOException {

    String api = "/api/files/1";

    String url = String.format("%s%s", BASE_URL, api);

    HttpGet httpGet = new HttpGet(url);

    CloseableHttpResponse response = httpClient.execute(httpGet);

    System.out.println(EntityUtils.toString(response.getEntity()));

}

使用HttpGet表示该连接为GET请求,HttpClient调用execute方法发送GET请求

PUT请求:

@Test

public void testPut() throws IOException {

    String api = "/api/user";

    String url = String.format("%s%s", BASE_URL, api);

    HttpPut httpPut = new HttpPut(url);

    UserVO userVO = UserVO.builder().name("h2t").id(16L).build();

    httpPut.setHeader("Content-Type", "application/json;charset=utf8");

    httpPut.setEntity(new StringEntity(JSONObject.toJSONString(userVO), "UTF-8"));

    CloseableHttpResponse response = httpClient.execute(httpPut);

    System.out.println(EntityUtils.toString(response.getEntity()));

}

POST请求:

@Test

public void testPost() throws IOException {

    String api = "/api/user";

    String url = String.format("%s%s", BASE_URL, api);

    HttpPost httpPost = new HttpPost(url);

    UserVO userVO = UserVO.builder().name("h2t2").build();

    httpPost.setHeader("Content-Type", "application/json;charset=utf8");

    httpPost.setEntity(new StringEntity(JSONObject.toJSONString(userVO), "UTF-8"));

    CloseableHttpResponse response = httpClient.execute(httpPost);

    System.out.println(EntityUtils.toString(response.getEntity()));

}

该请求是一个创建对象的请求,需要传入一个json字符串

上传文件

@Test

public void testUpload1() throws IOException {

    String api = "/api/files/1";

    String url = String.format("%s%s", BASE_URL, api);

    HttpPost httpPost = new HttpPost(url);

    File file = new File("~/Users/xin/docker_practice.pdf");

    FileBody fileBody = new FileBody(file);

    MultipartEntityBuilder builder = MultipartEntityBuilder.create();

    builder.setMode(HttpMultipartMode.BROWSER_COMPATIBLE);

    builder.addPart("file", fileBody);  //addPart上传文件

    HttpEntity entity = builder.build();

    httpPost.setEntity(entity);

    CloseableHttpResponse response = httpClient.execute(httpPost);

    System.out.println(EntityUtils.toString(response.getEntity()));

}

通过addPart上传文件

DELETE请求:

@Test

public void testDelete() throws IOException {

    String url = String.format("%s%s", BASE_URL, api);

    //请求参数

    Request request = new Request.Builder()

            .url(url)

            .delete()

            .build();

    final Call call = client.newCall(request);

    Response response = call.execute();

    System.out.println(response.body().string());

}

你可能感兴趣的:(2020-05-05)