java后端发送请求中附带文件

public Map<String, String> webUpload(Map<String, Object> param, MultipartFile file) throws Exception {

		String request_url = "xXXXXXXXXXXXXXXXXXXXXXXx";
		//上传文件
		// 换行符
		final String newLine = "\r\n";
		final String boundaryPrefix = "--";
		// 定义数据分隔线
		String BOUNDARY = "========7d4a6d158c9";
		// 服务器的域名
		URL url = new URL(request_url );
		HttpURLConnection conn = (HttpURLConnection) url.openConnection();
		// 设置为POST情
		conn.setRequestMethod("POST");
		// 发送POST请求必须设置如下两行
		conn.setDoOutput(true);
		conn.setDoInput(true);
		conn.setUseCaches(false);
		//设置请求头参数
		conn.setRequestProperty("connection", "Keep-Alive");
		conn.setRequestProperty("Charset", "UTF-8");
		conn.setRequestProperty("Content-Type", "multipart/form-data; boundary=" + BOUNDARY);
		OutputStream out = new DataOutputStream(conn.getOutputStream());
		//参数用户名user_name
		StringBuilder sb2 = new StringBuilder();
		sb2.append(boundaryPrefix);
		sb2.append(BOUNDARY);
		sb2.append(newLine);
		sb2.append("Content-Disposition: form-data;name=\"user_name\"");
		sb2.append(newLine);
		sb2.append(newLine);
		sb2.append(param.get("user_name"));
		sb2.append(newLine);
		out.write(sb2.toString().getBytes());

	
		// 上传文件
		StringBuilder sb = new StringBuilder();
		sb.append(boundaryPrefix);
		sb.append(BOUNDARY);
		sb.append(newLine);
		// 文件参数
		sb.append("Content-Disposition: form-data;name=\"print_file\";filename=\"" + param.get("fileName").toString()+ "\"" + newLine);
		sb.append("Content-Type: ").append(file.getContentType());
		// 参数头设置完以后需要两个换行,然后才是参数内容
		sb.append(newLine);
		sb.append(newLine);
		// 将参数头的数据写入到输出流中
		out.write(sb.toString().getBytes());
		// 数据输入流,用于读取文件数据
		DataInputStream in = new DataInputStream(file.getInputStream());
		byte[] bufferOut = new byte[1024];
		int bytes = 0;
		// 将文件数据写入到输出流中
		while ((bytes = in.read(bufferOut)) != -1) {
			out.write(bufferOut, 0, bytes);
		}
		/*
		 * 坑坑坑,不要再末尾添加空白,否则会被计入文件流,影响文件编码,office03、pdf因为会自动补位到1024的整数倍,因此无影响
		 */
		// out.write(newLine.getBytes());
		in.close();
		// 定义最后数据分隔线,即--加上BOUNDARY再加上--。
		byte[] end_data = (newLine + boundaryPrefix + BOUNDARY + boundaryPrefix + newLine)
				.getBytes();
		// 写上结尾标识
		out.write(end_data);
		out.flush();
		out.close();
		InputStream inputStream = conn.getInputStream();
		InputStreamReader inputStreamReader = new InputStreamReader(inputStream, "utf-8");
		// 定义BufferedReader输入流来读取URL的响应
		BufferedReader reader = new BufferedReader(inputStreamReader);
		String line = null;
		String result="";
		while ((line = reader.readLine()) != null) {
			result += line; //这里读取的是上边url对应的上传文件接口的返回值
		}
		//转xml为map
		Map<String, String> map = CommonUtils.xmlToMap(result);
		reader.close();
		inputStreamReader.close();
		// 释放资源
		inputStream.close();
		inputStream = null;
		conn.disconnect();
		return map;
	}
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 1
    评论
Java后端发送HttpPost请求的步骤如下: 1. 创建HttpClient对象。 2. 创建HttpPost对象,并设置请求的URL。 3. 设置请求参数,可以使用NameValuePair或者HttpEntity。 4. 执行请求,获取HttpResponse对象。 5. 解析HttpResponse对象,获取响应结果。 具体实现可以参考以下代码: ``` import java.io.IOException; import java.util.ArrayList; import java.util.List; import org.apache.http.HttpEntity; import org.apache.http.NameValuePair; import org.apache.http.client.ClientProtocolException; import org.apache.http.client.HttpClient; import org.apache.http.client.entity.UrlEncodedFormEntity; import org.apache.http.client.methods.HttpPost; import org.apache.http.impl.client.HttpClientBuilder; import org.apache.http.message.BasicNameValuePair; import org.apache.http.util.EntityUtils; public class HttpPostExample { public static void main(String[] args) { HttpClient httpClient = HttpClientBuilder.create().build(); HttpPost httpPost = new HttpPost("http://example.com/api"); List<NameValuePair> params = new ArrayList<NameValuePair>(); params.add(new BasicNameValuePair("param1", "value1")); params.add(new BasicNameValuePair("param2", "value2")); try { httpPost.setEntity(new UrlEncodedFormEntity(params)); httpPost.setHeader("Content-Type", "application/x-www-form-urlencoded"); HttpResponse httpResponse = httpClient.execute(httpPost); HttpEntity httpEntity = httpResponse.getEntity(); if (httpEntity != null) { String response = EntityUtils.toString(httpEntity); System.out.println(response); } } catch (ClientProtocolException e) { e.printStackTrace(); } catch (IOException e) { e.printStackTrace(); } } } ```

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值