Using HttpPost to upload files and HttpGet to make API requests (including HttpPost upload files) in Java

Java uses HttpPost to upload files and HttpGet to make API requests (including HttpPost upload files)

HttpPost Upload Files

public static String getSuffix(final MultipartFile file){
        if(file == null || file.getSize() == 0){
            return null;
        }
        String fileName = file.getOriginalFilename();
        return fileName.substring(fileName.lastIndexOf(".")+1);
    }
public static JSONObject uploadFile(String urlStr, MultipartFile file, String token) throws IOException {

        // Suffix
        String suffix = getSuffix(file);

        CloseableHttpClient httpClient = HttpClients.createDefault();
        HttpPost uploadFile = new HttpPost(urlStr);

        uploadFile.setHeader("authorization","Bearer " + token);

        DecimalFormat df = new DecimalFormat("#.##");
        MultipartEntityBuilder builder = MultipartEntityBuilder.create();
        //  HTTP.PLAIN_TEXT_TYPE,HTTP.UTF_8
        builder.addTextBody("name", file.getOriginalFilename(), ContentType.create("text/plain", Consts.UTF_8));
        builder.addTextBody("size", df.format((double) file.getSize() / 1024), ContentType.TEXT_PLAIN);
        builder.addTextBody("suffix", suffix, ContentType.TEXT_PLAIN);

        // Add files to HTTP post requests
                // String filepath = "/user/test/123.png"
        // File f = new File(filepath);
        builder.addBinaryBody(
                "file",
                file.getInputStream(),
                                // new FileInputStream(f),
                ContentType.APPLICATION_OCTET_STREAM,
                file.getOriginalFilename()
        );

        HttpEntity multipart = builder.build();
        uploadFile.setEntity(multipart);
        CloseableHttpResponse response = httpClient.execute(uploadFile);
        HttpEntity responseEntity = response.getEntity();
        String sResponse= EntityUtils.toString(responseEntity, "UTF-8");
        JSONObject jsonObject = JSONObject.parseObject(sResponse);

        // {"code":1,"data":"7efb19980373dd90f5077576afa7481a","message":""}
        // {"code":401,"httpStatus":null,"data":"373656a2-baff-423a-93fb-704f51003509","message":"error"}

        return jsonObject;

    }

HttpGet Requests API Get

Two ways:

  • Using splicing in URL s has been tested
  • The way parameters are constructed using URI is not tested

    1. Splicing in URL s

CloseableHttpClient httpClient = HttpClients.createDefault();
String urlStr ="http://abc.com/oss/getUrl?id=" + ossFileId;

HttpGet httpGet = new HttpGet(urlStr);
// Use Oauth2 for privilege verification
httpGet.setHeader("authorization","Bearer 34195fa8-00a6-4288-bda9-7d37541c3a39");
CloseableHttpResponse response = httpClient.execute(httpGet);

HttpEntity responseEntity = response.getEntity();
String sResponse= EntityUtils.toString(responseEntity, "UTF-8");
System.out.println(sResponse);
JSONObject jsonObject = JSONObject.parseObject(sResponse);
System.out.println(jsonObject);

2. How to use parameters

Since the parameters of GET requests are assembled behind the URL address, we need to build a URL with parameters.

        CloseableHttpClient httpClient = HttpClients.createDefault();
        
        URIBuilder uriBuilder = new URIBuilder("http://www.baidu.com");
        /** The first form of adding parameters */
        /*uriBuilder.addParameter("name", "root");
        uriBuilder.addParameter("password", "123456");*/
        /** The second way to add parameters */
        List<NameValuePair> list = new LinkedList<>();
        BasicNameValuePair param1 = new BasicNameValuePair("name", "root");
        BasicNameValuePair param2 = new BasicNameValuePair("password", "123456");
        list.add(param1);
        list.add(param2);
        uriBuilder.setParameters(list);
        // Constructing GET Request Objects Based on Parametric URI Objects
        HttpGet httpGet = new HttpGet(uriBuilder.build());
        // Use Oauth2 for privilege verification
        httpGet.setHeader("authorization","Bearer 34195fa8-00a6-4288-bda9-7d37541c3a39");
        CloseableHttpResponse response = httpClient.execute(httpGet);

        HttpEntity responseEntity = response.getEntity();
        String sResponse= EntityUtils.toString(responseEntity, "UTF-8");
        System.out.println(sResponse);
        JSONObject jsonObject = JSONObject.parseObject(sResponse);
        System.out.println(jsonObject);

Keywords: Java

Added by el-sid on Mon, 14 Oct 2019 17:54:55 +0300