HttpURLConnection form-data的post方式,提交图片信息

本文介绍了一个用于Android平台的图片上传工具类实现细节。该工具类通过POST请求将本地图片以multipart/form-data格式发送到服务器,并展示了如何处理JSON响应。文章涵盖了HTTPURLConnection的基本用法、文件读取及网络错误处理等内容。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >


package wuxi.mantoo.intelligentbag.util;

import java.io.BufferedReader;
import java.io.DataInputStream;
import java.io.DataOutputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.OutputStream;
import java.net.HttpURLConnection;
import java.net.MalformedURLException;
import java.net.URL;
import java.util.UUID;

import org.json.JSONException;
import org.json.JSONObject;

import wuxi.mantoo.intelligentbag.config.ManUrl;
import android.util.Log;

public class UpLoadPickture {

	private final String TAG = "UpLoadPickture";

	/* sumber server */
	public void uploadPickture(final String piktrueRoute) {

		/*
		 * visit server
		 */
		// next line
		final String newLine = "\r\n";
		final String boundaryPrefix = "--";
		// data division
		final String BOUNDARY = UUID.randomUUID().toString();

		new Thread() {

			public void run() {
				String target = ManUrl.UPLOAD; // 要提交的目标地址
				URL url;
				try {
					url = new URL(target);
					HttpURLConnection urlConn = (HttpURLConnection) url
							.openConnection(); // 创建一个HTTP连接
					urlConn.setRequestMethod("POST"); // 指定使用POST请求方式
					urlConn.setDoInput(true); // 向连接中写入数据
					urlConn.setDoOutput(true); // 从连接中读取数据
					urlConn.setUseCaches(false); // 禁止缓存
					urlConn.setInstanceFollowRedirects(true); // 自动执行HTTP重定向
					urlConn.setRequestProperty("connection", "Keep-Alive");
					urlConn.setRequestProperty("Charset", "UTF-8");
					urlConn.setRequestProperty("Content-Type",
							"multipart/form-data; boundary=" + BOUNDARY); // 设置内容类型
					DataOutputStream out = new DataOutputStream(
							urlConn.getOutputStream()); // 获取输出流

					// 上传文件
					File file = new File(piktrueRoute);
					StringBuilder sb = new StringBuilder();
					sb.append(boundaryPrefix);
					sb.append(BOUNDARY);
					sb.append(newLine);

					/**
					 *文件参数,photo参数名可以随意修改
					 *photo 为服务器的key
					 *如果服务器设置了这个key就要改成响应的参数
					*/
					sb.append("Content-Disposition: form-data;name=\"photo\";filename=\""
							+ file.getName() + "\"" + 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;
					// 每次读1KB数据,并且将文件数据写入到输出流中
					while ((bytes = in.read(bufferOut)) != -1) {
						out.write(bufferOut, 0, bytes);
					}
					// 最后添加换行
					out.write(newLine.getBytes());
					in.close();

					// 定义最后数据分隔线,即--加上BOUNDARY再加上--。
					byte[] end_data = (newLine + boundaryPrefix + BOUNDARY
							+ boundaryPrefix + newLine).getBytes();
					// 写上结尾标识
					out.write(end_data);
					out.flush(); // 输出缓存
					out.close(); // 关闭数据输出流
					Log.i(TAG, "getResponseCode:" + urlConn.getResponseCode());
					if (urlConn.getResponseCode() == HttpURLConnection.HTTP_OK) { // 判断是否响应成功
						InputStreamReader in1 = new InputStreamReader(
								urlConn.getInputStream(), "utf-8"); // 获得读取的内容,utf-8获取内容的编码
						BufferedReader buffer = new BufferedReader(in1); // 获取输入流对象
						String inputLine = null;
						Log.d(TAG, "inputLine:" + buffer.readLine());
						while ((inputLine = buffer.readLine()) != null) {
							Log.d(TAG, inputLine + "\n");
							try {
								JSONObject reader = new JSONObject(inputLine);// 使用JSONObject解析
								JSONObject reObjectData = reader
										.getJSONObject("data");

							} catch (JSONException e) {
								// TODO Auto-generated catch block
								e.printStackTrace();
								Log.i(TAG, e.getMessage());
							}
						}

						in1.close(); // 关闭字符输入流
					}
					urlConn.disconnect(); // 断开连接
				} catch (MalformedURLException e) {
					e.printStackTrace();
					Log.i(TAG, e.getMessage());
				} catch (IOException e) {
					e.printStackTrace();
					Log.i(TAG, e.getMessage());
				}
			};
		}.start();

	}

}


在Java中,使用`HttpURLConnection`或基于Java的HTTP客户端库(例如`Apache HttpClient`、`RestAssured` 或 `Spring Framework`)发送POST请求并传递表单数据(Form Data),你需要按照以下步骤操作: 1. **使用`HttpURLConnection`**: ```java import java.io.OutputStream; import java.net.HttpURLConnection; import java.net.URL; public class FormDataExample { public static void main(String[] args) throws Exception { String url = "http://example.com/api/endpoint"; URL obj = new URL(url); HttpURLConnection con = (HttpURLConnection) obj.openConnection(); // 设置POST请求 con.setRequestMethod("POST"); con.setRequestProperty("Content-Type", "application/x-www-form-urlencoded"); // 添加表单数据到请求体 String formData = "key=value&another_key=another_value"; con.setDoOutput(true); // 开启输出流 try(OutputStream os = con.getOutputStream()) { byte[] formDataBytes = formData.getBytes("UTF-8"); os.write(formDataBytes); } int responseCode = con.getResponseCode(); if (responseCode == HttpURLConnection.HTTP_OK) { System.out.println("Response: " + readResponse(con)); } } private static String readResponse(HttpURLConnection connection) throws IOException { StringBuilder result = new StringBuilder(); BufferedReader in = new BufferedReader(new InputStreamReader(connection.getInputStream())); String inputLine; while ((inputLine = in.readLine()) != null) { result.append(inputLine); } return result.toString(); } } ``` 2. **使用`Apache HttpClient`**: ```java import org.apache.http.client.methods.CloseableHttpResponse; import org.apache.http.client.methods.HttpPost; import org.apache.http.entity.StringEntity; import org.apache.http.impl.client.CloseableHttpClient; import org.apache.http.impl.client.HttpClients; public class HttpClientFormDataExample { public static void main(String[] args) throws Exception { CloseableHttpClient httpClient = HttpClients.createDefault(); HttpPost httpPost = new HttpPost("http://example.com/api/endpoint"); // 添加表单数据 httpPost.setEntity(new StringEntity("key=value&another_key=another_value", "UTF-8")); httpPost.setHeader("Content-type", "application/x-www-form-urlencoded"); CloseableHttpResponse response = httpClient.execute(httpPost); // ...处理响应... } } ```
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值