1. 程式人生 > >以httpClient通過代理上傳檔案

以httpClient通過代理上傳檔案

public void proxyUploadFile() throws IOException {
    CloseableHttpClient httpclient = HttpClients.createDefault();
    try {
        HttpHost target = new HttpHost("192.168.71.128", 8080); //目的伺服器地址
HttpHost proxy = new HttpHost("172.16.44.22", 9901, "http"); //代理伺服器地址
RequestConfig config = RequestConfig.custom
().setProxy(proxy).build(); HttpPost request = new HttpPost("/upload/file/"); //目的伺服器上傳檔案介面 request.setConfig(config); //add file File file = new File("/home/mydoc.docx"); HttpEntity data = MultipartEntityBuilder.create().setMode(HttpMultipartMode.BROWSER_COMPATIBLE).addPart("file", new
FileBody(file)).build(); request.setEntity(data); getLogger().info("Executing request " + request.getRequestLine() + " to " + target + " via " + proxy); CloseableHttpResponse response = httpclient.execute(target, request); try { getLogger().info("----------------------------------------"
); getLogger().info(response.getStatusLine()); getLogger().info(EntityUtils.toString(response.getEntity())); //呼叫上傳檔案介面返回結果 } finally { IOUtils.closeQuietly(response); } } finally { IOUtils.closeQuietly(httpclient); } return; }