java post上传进度_Java模拟post请求上传文件

Java代码实现

/**

* 模拟文件post上传

* @param urlStr(接口地址)

* @param formName(接口file接收名)

* @param fileName(需要上传文件的本地路径)

* @return文件上传到接口返回的结果

*/

public static String uploadFile(String urlStr, String formName, String fileName) {

String baseResult = null;

try {

final String newLine = "\r\n";

final String boundaryPrefix = "--";

String BOUNDARY = "========7d4a6d158c9";// 模拟数据分隔线

URL url = new URL(urlStr);

HttpURLConnection conn = (HttpURLConnection) url.openConnection();

conn.setRequestMethod("POST");// 设置为POST请求

conn.setDoOutput(true);

conn.setDoInput(true);

conn.setRequestProperty("connection", "Keep-Alive");// 设置请求头参数

conn.setRequestProperty("Charsert", "UTF-8");

conn.setRequestProperty("Content-Type","multipart/form-data; boundary=" + BOUNDARY);

OutputStream out = conn.getOutputStream();

File file = new File(fileName);

StringBuilder sb = new StringBuilder();

sb.append(boundaryPrefix);

sb.append(BOUNDARY);

sb.append(newLine);

sb.append("Content-Disposition: form-data;name=\""+formName+"\";filename=\""+ fileName + "\"" + newLine);

sb.append("Content-Type:application/octet-stream");

sb.append(newLine);

sb.append(newLine);

out.write(sb.toString().getBytes());// 将参数头的数据写入到输出流中

DataInputStream in = new DataInputStream(new FileInputStream(file));// 数据输入流,用于读取文件数据

byte[] bufferOut = new byte[1024];

int bytes = 0;

while ((bytes = in.read(bufferOut)) != -1) {// 每次读1KB数据,并且将文件数据写入到输出流中

out.write(bufferOut, 0, bytes);

}

out.write(newLine.getBytes());

in.close();

byte[] end_data = (newLine + boundaryPrefix + BOUNDARY

+ boundaryPrefix + newLine).getBytes();

out.write(end_data);

out.flush();

out.close();

BufferedReader reader = new BufferedReader(new InputStreamReader(

conn.getInputStream()));

String line = null;

StringBuffer strs = new StringBuffer("");

while ((line = reader.readLine()) != null) {

strs.append(line);

}

baseResult = strs;

} catch (Exception e) {

baseResult = e.getMessage();

}

return baseResult;

}

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
以下是Java中使用POST请求上传文件的示例代码: ```java import java.io.File; import java.io.IOException; import org.apache.http.HttpEntity; import org.apache.http.HttpResponse; import org.apache.http.client.ClientProtocolException; import org.apache.http.client.HttpClient; 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.MultipartEntityBuilder; import org.apache.http.entity.mime.content.FileBody; import org.apache.http.impl.client.HttpClientBuilder; import org.apache.http.util.EntityUtils; public class FileUploader { public static void main(String[] args) { String url = "http://example.com/upload"; String filePath = "/path/to/file"; HttpClient httpClient = HttpClientBuilder.create().build(); HttpPost httpPost = new HttpPost(url); MultipartEntityBuilder builder = MultipartEntityBuilder.create(); builder.setMode(HttpMultipartMode.BROWSER_COMPATIBLE); File file = new File(filePath); FileBody fileBody = new FileBody(file, ContentType.DEFAULT_BINARY); builder.addPart("file", fileBody); HttpEntity entity = builder.build(); httpPost.setEntity(entity); try { HttpResponse response = httpClient.execute(httpPost); HttpEntity responseEntity = response.getEntity(); String responseString = EntityUtils.toString(responseEntity, "UTF-8"); System.out.println(responseString); } catch (ClientProtocolException e) { e.printStackTrace(); } catch (IOException e) { e.printStackTrace(); } } } ``` 在这个示例中,我们使用了Apache HttpClient库来发送POST请求。我们首先创建一个HttpClient实例,然后创建一个HttpPost实例,并将要上传文件添加到MultipartEntityBuilder中。最后,我们将MultipartEntityBuilder构建为一个HttpEntity,并将其设置为HttpPost的实体。最后,我们执行HttpPost请求并获取响应。
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值