Java中使用HttpPost上傳文件以及HttpGet進行API請求(包含HttpPost上傳文件)


Java中使用HttpPost上傳文件以及HttpGet進行API請求(包含HttpPost上傳文件)

一、HttpPost上傳文件

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 {

        // 后綴
        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);

        // 把文件加到HTTP的post請求中
				// 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對API進行Get請求

兩種方式:

  • 使用在URL中拼接,已經進行過測試
  • 使用URI進行參數構造的方式未進行測試

1、在URL中拼接

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

HttpGet httpGet = new HttpGet(urlStr);
// 使用Oauth2進行權限驗證
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、使用參數的方式

由於GET請求的參數都是拼裝在URL地址后方,所以我們要構建一個URL,帶參數

		CloseableHttpClient httpClient = HttpClients.createDefault();
		
        URIBuilder uriBuilder = new URIBuilder("http://www.baidu.com");
        /** 第一種添加參數的形式 */
        /*uriBuilder.addParameter("name", "root");
        uriBuilder.addParameter("password", "123456");*/
        /** 第二種添加參數的形式 */
        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);
        // 根據帶參數的URI對象構建GET請求對象
        HttpGet httpGet = new HttpGet(uriBuilder.build());
        // 使用Oauth2進行權限驗證
        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);


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM