Java使用HttpClient上传文件

简介: Java可以使用HttpClient发送Http请求、上传文件等,非常的方便 Maven org.apache.httpcomponents httpclient 4.5.3 org.

Java可以使用HttpClient发送Http请求、上传文件等,非常的方便

Maven

<dependency>
	<groupId>org.apache.httpcomponents</groupId>
	<artifactId>httpclient</artifactId>
	<version>4.5.3</version>
</dependency>
<dependency>
	<groupId>org.apache.httpcomponents</groupId>
	<artifactId>httpmime</artifactId>
	<version>4.5.3</version>
</dependency>

上传代码1:

 public static void upload2() throws ClientProtocolException, IOException{
	CloseableHttpClient httpClient = HttpClientBuilder.create().build();
	CloseableHttpResponse httpResponse = null;
	RequestConfig requestConfig = RequestConfig.custom().setConnectTimeout(200000).setSocketTimeout(200000000).build();
	HttpPost httpPost = new HttpPost("http://localhost:8080/WEY.WebApp/auth/right/right/receiveFile.html");
	httpPost.setConfig(requestConfig);
	MultipartEntityBuilder multipartEntityBuilder = MultipartEntityBuilder.create();
	//multipartEntityBuilder.setCharset(Charset.forName("UTF-8"));
		
	//File file = new File("F:\\Ken\\1.PNG");
	//FileBody bin = new FileBody(file);  
		
	File file = new File("F:\\Ken\\abc.pdf");
		 
	//multipartEntityBuilder.addBinaryBody("file", file,ContentType.create("image/png"),"abc.pdf");
	//当设置了setSocketTimeout参数后,以下代码上传PDF不能成功,将setSocketTimeout参数去掉后此可以上传成功。上传图片则没有个限制
	//multipartEntityBuilder.addBinaryBody("file",file,ContentType.create("application/octet-stream"),"abd.pdf"); 
	multipartEntityBuilder.addBinaryBody("file",file);
	//multipartEntityBuilder.addPart("comment", new StringBody("This is comment", ContentType.TEXT_PLAIN));
	multipartEntityBuilder.addTextBody("comment", "this is comment");
	HttpEntity httpEntity = multipartEntityBuilder.build();
	httpPost.setEntity(httpEntity);
		
	httpResponse = httpClient.execute(httpPost);
	HttpEntity responseEntity = httpResponse.getEntity();
	int statusCode= httpResponse.getStatusLine().getStatusCode();
	if(statusCode == 200){
		BufferedReader reader = new BufferedReader(new InputStreamReader(responseEntity.getContent()));
		StringBuffer buffer = new StringBuffer();
		String str = "";
		while(!StringUtil.isRealEmpty(str = reader.readLine())) {
			buffer.append(str);
		}
			
		System.out.println(buffer.toString());
	}
		
	httpClient.close();
	if(httpResponse!=null){
		httpResponse.close();
	}
	
}

上传代码2:

 public static void upload() {  
        CloseableHttpClient httpclient = HttpClients.createDefault();  
        //CloseableHttpClient httpclient = HttpClientBuilder.create().build();
        try {  
            HttpPost httppost = new HttpPost("http://localhost:8080/WEY.WebApp/auth/right/right/receiveFile.html");  
  
            RequestConfig requestConfig = RequestConfig.custom().setConnectTimeout(200000).setSocketTimeout(200000).build();
            httppost.setConfig(requestConfig);
            
            FileBody bin = new FileBody(new File("F:\\Ken\\abc.pdf"));  
            StringBody comment = new StringBody("This is comment", ContentType.TEXT_PLAIN);  
  
            HttpEntity reqEntity = MultipartEntityBuilder.create().addPart("file", bin).addPart("comment", comment).build();  
  
            httppost.setEntity(reqEntity);  
  
            System.out.println("executing request " + httppost.getRequestLine());  
            CloseableHttpResponse response = httpclient.execute(httppost);  
            try {  
                System.out.println(response.getStatusLine());  
                HttpEntity resEntity = response.getEntity();  
                if (resEntity != null) {  
                	String responseEntityStr = EntityUtils.toString(response.getEntity());
                	System.out.println(responseEntityStr);
                    System.out.println("Response content length: " + resEntity.getContentLength());  
                }  
                EntityUtils.consume(resEntity);  
            } finally {  
                response.close();  
            }  
        } catch (ClientProtocolException e) {  
            e.printStackTrace();  
        } catch (IOException e) {  
            e.printStackTrace();  
        } finally {  
            try {  
                httpclient.close();  
            } catch (IOException e) {  
                e.printStackTrace();  
            }  
        }  
    }
普通POST请求
public String post() throws ClientProtocolException, IOException{
	CloseableHttpClient httpClient = HttpClientBuilder.create().build();
	CloseableHttpResponse httpResponse = null;
	HttpPost httpPost = new HttpPost("http://localhost:8080/WEY.WebApp/auth/right/right/receivePost.html");
	RequestConfig requestConfig = RequestConfig.custom().setConnectTimeout(20000).setSocketTimeout(22000).build();
	httpPost.setConfig(requestConfig);
	List<NameValuePair> params = new ArrayList<NameValuePair>();
	params.add(new BasicNameValuePair("user.loginId", "Lin"));
	params.add(new BasicNameValuePair("user.employeeName","令狐冲"));
	UrlEncodedFormEntity entity = new UrlEncodedFormEntity(params,Charset.forName("UTF-8"));
	httpPost.setEntity(entity);
	httpResponse = httpClient.execute(httpPost);
	HttpEntity responseEntity = httpResponse.getEntity();
	if(responseEntity!=null){
		String content = EntityUtils.toString(responseEntity,"UTF-8");
		System.out.println(content);
	}
		
	if(httpResponse!=null){
		httpResponse.close();
	}
	if(httpClient!=null){
		httpClient.close();
	}
	return null;
}
	

  

目录
相关文章
|
1月前
|
弹性计算 前端开发 小程序
微信小程序上传文件至阿里云OSS直传(java后端签名+前端直传)
当前的通用文件上传方式是通过前端上传到服务器,再由服务器转存至对象存储。这种方式在处理小文件时效率尚可,但大文件上传因受限于服务器带宽,速度较慢。例如,一个100MB的文件在5Mbps带宽的阿里云ECS上上传至服务器需160秒。为解决此问题,可以采用后端签名的方式,使微信小程序直接上传文件到阿里云OSS,绕过服务器中转。具体操作包括在JAVA后端引入相关依赖,生成签名,并在微信小程序前端使用这个签名进行文件上传,注意设置正确的请求头和formData参数。这样能提高大文件上传的速度。
|
网络协议 安全 Java
Java通过OpenSSH上传文件到远程Windows服务器,并远程解压zip包
Java通过OpenSSH上传文件到远程Windows服务器,并远程解压zip包
1120 0
Java通过OpenSSH上传文件到远程Windows服务器,并远程解压zip包
|
22天前
|
Java Spring
上传文件出现 aximum upload size exceeded; nested exception is java.lang.IllegalStateException: org.apache.
上传文件出现 aximum upload size exceeded; nested exception is java.lang.IllegalStateException: org.apache.
9 0
|
存储 Java Spring
Java实现上传文件到指定服务器指定目录
Java实现上传文件到指定服务器指定目录
2173 0
|
Java Apache Spring
Java发送Http请求(HttpClient)
Java发送Http请求(HttpClient)
7162 1
|
9月前
|
应用服务中间件
Minio上传文件之后出现java.io.UncheckedIOException: Cannot delete D:/temp/tomcat问题的解决
Minio上传文件之后出现java.io.UncheckedIOException: Cannot delete D:/temp/tomcat问题的解决
376 0
|
Java fastjson Maven
写给大忙人看的 - Java中上传文件MinIO服务器(2)
上一篇 写给大忙人看的 - 搭建文件服务器 MinIO(一),我们已经成功地搭建了 MinIO 文件服务器,这一篇讲解在 Java 中如何上传文件至 MinIO
488 0
写给大忙人看的 - Java中上传文件MinIO服务器(2)
|
10月前
|
Java
向服务器端上传文件(Java代码)
向服务器端上传文件(Java代码)
225 0
|
10月前
|
Java Linux Shell
java上传文件到sftp服务器
最近公司有个数据对接需求,合作方那边是使用我们这边的系统进行出单的,数据首先也是在我们这边。后面他们自己开发了业务系统,需要我们这边定时把每天的数据传送到那边去。他们那边开发部门要求我们这边,按一定的格式导出加签加密的数据文件到他们的sftp服务器上面去。
192 0
|
11月前
|
Java
解决java项目上传文件后必须重启才能显示图片问题
解决java项目上传文件后必须重启才能显示图片问题