天天看點

java使用httpclient調用上傳圖檔接口[示例]

參考網站: nodejs使用http子產品編寫上傳圖檔接口測試用戶端

如果是java控制台app可以前往

http://hc.apache.org/downloads.cgi

下載下傳新版httpclient庫

java使用httpclient調用上傳圖檔接口[示例]

示例

調用上傳圖檔接口代碼示例:

import org.apache.http.Consts;
import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.NameValuePair;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.entity.ContentType;
import org.apache.http.entity.mime.MultipartEntityBuilder;
import org.apache.http.entity.mime.content.FileBody;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClients;
import org.apache.http.message.BasicNameValuePair;
import org.apache.http.util.EntityUtils;

import java.io.File;
import java.io.IOException;
import java.nio.charset.Charset;
import java.util.ArrayList;
import java.util.List;

public class Main {
    public static void main(String[] args) {
        CloseableHttpClient httpClient = HttpClients.createDefault();
        HttpPost httpPost = new HttpPost("http://127.0.0.1:5000/");//建立HttpPost對象,改成自己的位址
        File file = new File("C:\\temp.png");//相對路徑使用不了的話,使用圖檔絕對路徑
        if(!file.exists()){//判斷檔案是否存在
            System.out.print("檔案不存在");
            return;
        }
        FileBody bin = new FileBody(file, ContentType.create("image/png", Consts.UTF_8));//建立圖檔送出主體資訊
        HttpEntity entity = MultipartEntityBuilder
                .create()
                .setCharset(Charset.forName("utf-8"))
                .addPart("file", bin)//添加到請求
                .build();
        httpPost.setEntity(entity);
        HttpResponse response= null;//發送Post,并傳回一個HttpResponse對象
        try {
            response = httpClient.execute(httpPost);
            if(response.getStatusLine().getStatusCode()==200) {//如果狀态碼為200,就是正常傳回
                String result = EntityUtils.toString(response.getEntity());
                System.out.print(result);
            }
        } catch (IOException e) {
            e.printStackTrace();
        }
        System.out.print(response);
        System.out.print("結束");
    }
}