http客户端

Jboot内置了一个轻量级的http客户端,可以通过这个客户端方便的对其他第三方http服务器进行数据请求和下载等功能。

Get请求

  1. @Test
  2. public void testHttpGet(){
  3. String html = Jboot.httpGet("https://www.baidu.com");
  4. System.out.println(html);
  5. }

或者

  1. @Test
  2. public void testHttpPost(){
  3. Map<String, Object> params = new HashMap<>();
  4. params.put("key1","value1");
  5. params.put("key2","value2");
  6. String html = Jboot.httpGet("http://www.oschina.net/",params);
  7. System.out.println(html);
  8. }

Post请求

  1. @Test
  2. public void testHttpPost(){
  3. String html = Jboot.httpPost("http://www.xxx.com");
  4. System.out.println(html);
  5. }

或者

  1. @Test
  2. public void testHttpPost(){
  3. Map<String, Object> params = new HashMap<>();
  4. params.put("key1","value1");
  5. params.put("key2","value2");
  6. String html = Jboot.httpPost("http://www.oschina.net/",params);
  7. System.out.println(html);
  8. }

文件上传

  1. @Test
  2. public void testHttpUploadFile(){
  3. Map<String, Object> params = new HashMap<>();
  4. params.put("file1",file1);
  5. params.put("file2",file2);
  6. String html = Jboot.httpPost("http://www.oschina.net/",params);
  7. System.out.println(html);
  8. }

备注:文件上传其实和post提交是一样的,只是params中的参数是文件。

文件下载

  1. @Test
  2. public void testHttpDownload() {
  3. String url = "http://www.xxx.com/abc.zip";
  4. File downloadToFile = new File("/xxx/abc.zip");
  5. JbootHttpRequest request = JbootHttpRequest.create(url, null, JbootHttpRequest.METHOD_GET);
  6. request.setDownloadFile(downloadToFile);
  7. JbootHttpResponse response = Jboot.me().getHttp().handle(request);
  8. if (response.isError()){
  9. downloadToFile.delete();
  10. }
  11. System.out.println(downloadToFile.length());
  12. }