java模拟post请求上传文件到另一远程接口(content-type:multipart/form-data)
发布日期:2021-10-16 10:03:52 浏览次数:29 分类:技术文章

本文共 1209 字,大约阅读时间需要 4 分钟。

在开发过程中,我需要调用另一文件上传接口,该接口要求是post提交,content-type:multipart/form-data,因此首先将文件写入本地存储路径,并将该文件按照post传输,代码如下,亲测成功:

public static String sendPostWithFile(File lrcFile, String urlStr) throws Exception{       String BOUNDARY = java.util.UUID.randomUUID().toString();       MultipartEntity multipartEntity = new MultipartEntity(HttpMultipartMode.BROWSER_COMPATIBLE, "--------------------"+BOUNDARY, Charset.defaultCharset());       multipartEntity.addPart("lyricsUpload", new FileBody(lrcFile));    //lyricsUpload文件名       HttpPost request = new HttpPost(urlStr);    //远程接口       request.setEntity(multipartEntity);       request.addHeader("Content-Type", "multipart/form-data; boundary=--------------------"+BOUNDARY);       DefaultHttpClient httpClient = new DefaultHttpClient();       HttpResponse response = httpClient.execute(request);       InputStream is = response.getEntity().getContent();       BufferedReader in = new BufferedReader(new InputStreamReader(is));       StringBuffer buffer = new StringBuffer();       String line = "";       while ((line = in.readLine()) != null) {           buffer.append(line);       }       System.out.println("发送消息收到的返回:"+buffer.toString());       return buffer.toString();}

 

转载地址:https://blog.csdn.net/small__snail__5/article/details/88717456 如侵犯您的版权,请留言回复原文章的地址,我们会给您删除此文章,给您带来不便请您谅解!

上一篇:常用的正则字母大小写转换
下一篇:java程序调用http请求

发表评论

最新留言

感谢大佬
[***.8.128.20]2024年03月28日 06时49分05秒