• 微信公众号:美女很有趣。 工作之余,放松一下,关注即送10G+美女照片!

将文件转换为文件流进行上传(例:通过HDMI进行传输)

开发技术 开发技术 4小时前 3次浏览

package com.boottest.app; import org.apache.commons.codec.Charsets; 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.HttpMultipartMode; import org.apache.http.entity.mime.MultipartEntity; 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.DefaultHttpClient; import org.apache.http.impl.client.HttpClients; import org.apache.http.message.BasicNameValuePair; import org.apache.http.util.EntityUtils; import java.io.*; import java.nio.charset.Charset; import java.util.ArrayList; import java.util.List; public class FileTest { public static void main(String[] args) throws Exception { String url ="http://localhost:8200/sys/uploadfile/uploadFile"; InputStream inputStream=new FileInputStream("C:\Users\Administrator\Desktop\work_order1.txt");; List<NameValuePair> params=new ArrayList<NameValuePair>(); params.add(new BasicNameValuePair("file_real_name","work_order1.txt")); String Result=postInputStream(url,inputStream,"work_order1.txt",params); System.out.println("发送消息收到的返回:"+Result); } public static String postInputStream(String requestUrl,InputStream inputStream, String fileName, List<NameValuePair> params) throws Exception { try { CloseableHttpClient httpClient = HttpClients.createDefault(); // 创建 POST请求 HttpPost httpPost = new HttpPost(requestUrl); // 构建多组件 Entrity构建器 MultipartEntityBuilder builder = MultipartEntityBuilder.create(); builder.setCharset(Charsets.UTF_8); builder.setMode(HttpMultipartMode.BROWSER_COMPATIBLE); //文件传输http请求头(multipart/form-data) builder.addBinaryBody("file", inputStream, ContentType.MULTIPART_FORM_DATA, fileName);// 文件流 //字节传输http请求头(application/json) ContentType contentType = ContentType.create("application/json", Charsets.UTF_8); for (NameValuePair param : params) { // 传输字节流 builder.addTextBody(param.getName(), param.getValue(), contentType); } HttpEntity entity = builder.build(); httpPost.setEntity(entity); HttpResponse response = httpClient.execute(httpPost); // 执行提交 HttpEntity responseEntity = response.getEntity(); if (responseEntity != null) { // 将响应内容转换为字符串 return EntityUtils.toString(responseEntity, Charsets.UTF_8); } } catch (Exception e) { throw new Exception("post请求失败,"+e.getMessage()); } return ""; } }

  

所需pom依赖:
<dependency>
    <groupId>org.apache.httpcomponents</groupId>
    <artifactId>httpclient</artifactId>
    <version>4.5</version>
</dependency>
<dependency>
    <groupId>org.apache.httpcomponents</groupId>
    <artifactId>httpmime</artifactId>
    <version>4.5</version>
</dependency>

 


喜欢 (0)