HttpURLConnection POST 上传文件

package com.popo.http;

import java.io.ByteArrayOutputStream;
import java.io.DataOutputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.InputStream;
import java.net.HttpURLConnection;
import java.net.SocketTimeoutException;
import java.net.URL;
import java.net.URLEncoder;
import java.util.HashMap;
import java.util.Iterator;
import java.util.Map;
import java.util.Set;

import javax.imageio.ImageIO;
import javax.imageio.ImageReader;
import javax.imageio.stream.ImageInputStream;

public class HttpPostUtil {
	URL url;
	HttpURLConnection conn;
	String boundary = "--------httppost123";
	Map<String, String> textParams = new HashMap<String, String>();
	Map<String, File> fileparams = new HashMap<String, File>();
	DataOutputStream ds;

	public HttpPostUtil(String url) throws Exception {
		this.url = new URL(url);
	}
    //重新设置要请求的服务器地址,即上传文件的地址。
	public void setUrl(String url) throws Exception {
		this.url = new URL(url);
	}
    //增加一个普通字符串数据到form表单数据中
	public void addTextParameter(String name, String value) {
		textParams.put(name, value);
	}
    //增加一个文件到form表单数据中
	public void addFileParameter(String name, File value) {
		fileparams.put(name, value);
	}
    // 清空所有已添加的form表单数据
	public void clearAllParameters() {
		textParams.clear();
		fileparams.clear();
	}
    // 发送数据到服务器,返回一个字节包含服务器的返回结果的数组
	public byte[] send() throws Exception {
		initConnection();
		try {
			conn.connect();
		} catch (SocketTimeoutException e) {
			// something
			throw new RuntimeException();
		}
		ds = new DataOutputStream(conn.getOutputStream());
		writeFileParams();
		writeStringParams();
		paramsEnd();
		InputStream in = conn.getInputStream();
		ByteArrayOutputStream out = new ByteArrayOutputStream();
		int b;
		while ((b = in.read()) != -1) {
			out.write(b);
		}
		out.flush();
		conn.disconnect();
		return out.toByteArray();
	}
    //文件上传的connection的一些必须设置
	private void initConnection() throws Exception {
		conn = (HttpURLConnection) this.url.openConnection();
		conn.setDoOutput(true);
		conn.setUseCaches(false);
		conn.setConnectTimeout(10000); //连接超时为10秒
		conn.setRequestMethod("POST");
		conn.setRequestProperty("Content-Type",
				"multipart/form-data; boundary=" + boundary);
		conn.setChunkedStreamingMode(1024 * 50);
	}
    //普通字符串数据
	private void writeStringParams() throws Exception {
		Set<String> keySet = textParams.keySet();
		for (Iterator<String> it = keySet.iterator(); it.hasNext();) {
			String name = it.next();
			String value = textParams.get(name);
			ds.writeBytes("--" + boundary + "\r\n");
			ds.writeBytes("Content-Disposition: form-data; name=\"" + name
					+ "\"\r\n");
			ds.writeBytes("\r\n");
			ds.writeBytes(encode(value) + "\r\n");
		}
	}
    //文件数据
	private void writeFileParams() throws Exception {
		Set<String> keySet = fileparams.keySet();
		for (Iterator<String> it = keySet.iterator(); it.hasNext();) {
			String name = it.next();
			File value = fileparams.get(name);
			ds.writeBytes("--" + boundary + "\r\n");
			ds.writeBytes("Content-Disposition: form-data; name=\"" + name
					+ "\"; filename=\"" + encode(value.getName()) + "\"\r\n");
			ds.writeBytes("Content-Type: " + getContentType(value) + "\r\n");
			ds.writeBytes("\r\n");
			ds.write(getBytes(value));
			ds.writeBytes("\r\n");
		}
	}
    //获取文件的上传类型,图片格式为image/png,image/jpg等。非图片为application/octet-stream
	private String getContentType(File f) throws Exception {
		
//		return "application/octet-stream";  // 此行不再细分是否为图片,全部作为application/octet-stream 类型
		ImageInputStream imagein = ImageIO.createImageInputStream(f);
		if (imagein == null) {
			return "application/octet-stream";
		}
		Iterator<ImageReader> it = ImageIO.getImageReaders(imagein);
		if (!it.hasNext()) {
			imagein.close();
			return "application/octet-stream";
		}
		imagein.close();
		return "image/" + it.next().getFormatName().toLowerCase();//将FormatName返回的值转换成小写,默认为大写

	}
    //把文件转换成字节数组
	private byte[] getBytes(File f) throws Exception {
		FileInputStream in = new FileInputStream(f);
		ByteArrayOutputStream out = new ByteArrayOutputStream();
		byte[] b = new byte[1024];
		int n;
		while ((n = in.read(b)) != -1) {
			out.write(b, 0, n);
		}
		in.close();
		return out.toByteArray();
	}
	//添加结尾数据
	private void paramsEnd() throws Exception {
		ds.writeBytes("--" + boundary + "--" + "\r\n");
		ds.writeBytes("\r\n");
	}
	// 对包含中文的字符串进行转码,此为UTF-8。服务器那边要进行一次解码
    private String encode(String value) throws Exception{
    	return URLEncoder.encode(value, "UTF-8");
    }
	public static void main(String[] args) throws Exception {
		HttpPostUtil u = new HttpPostUtil("http://localhost");
		u.addFileParameter("img", new File(
				"165247.txt"));
		u.addTextParameter("text", "中文");
		byte[] b = u.send();
		String result = new String(b);
		System.out.println(result);

	}

}
原文来自:http://314858770.iteye.com/blog/720456

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
### 回答1: HttpURLConnection 是 Java 的标准类库之一,可以用来发送 HTTP 请求。它支持 GET、POST、HEAD、OPTIONS、PUT、DELETE 和 TRACE 方法。可以使用 HttpURLConnection 类来发送 HTTP POST 请求。通常使用 HttpURLConnection 类发送 POST 请求时,需要设置请求头信息和请求参数。下面是一个示例代码: ``` URL url = new URL("http://www.example.com"); HttpURLConnection connection = (HttpURLConnection) url.openConnection(); connection.setRequestMethod("POST"); connection.setDoOutput(true); connection.setDoInput(true); connection.setUseCaches(false); connection.setInstanceFollowRedirects(true); connection.setRequestProperty("Content-Type", "application/x-www-form-urlencoded"); connection.connect(); DataOutputStream out = new DataOutputStream(connection.getOutputStream()); out.writeBytes("param1=value1&param2=value2"); out.flush(); out.close(); BufferedReader reader = new BufferedReader(new InputStreamReader(connection.getInputStream())); String lines; StringBuffer sb = new StringBuffer(""); while ((lines = reader.readLine()) != null) { sb.append(lines); } System.out.println(sb.toString()); ``` 以上代码使用了 HttpURLConnection 发送一个 HTTP POST 请求,并设置了一些请求头信息(如 Content-Type)和请求参数。 注意:如果你在使用这个类发送请求时遇到了问题,请检查服务端是否支持该请求方法。 ### 回答2: HttpURLConnection Post是一种与服务器进行HTTP协议通信的方法。它是HttpURLConnection的子类,可以方便地发送POST请求并接收服务器响应。要使用HttpURLConnectionPOST方法,需要设置好URLConnection的请求属性,并根据需要写入请求正文数据,并接收返回的响应数据。 具体实现流程如下: 1. 创建HttpURLConnection连接对象,并设置请求的URL地址。 2. 通过setRequestMethod()方法设置POST方式。 3. 设置URLConnection的一些请求属性,如请求超时时间、接收数据超时时间等。 4. 如果需要向服务器发送请求正文数据,则需要在HttpURLConnection对象中开启输出流(setDoOutput(true))并写入正文数据(如表单参数、JSON参数等)。 5. 向服务器发送请求,调用HttpURLConnection的connect()方法。 6. 接收服务器返回的响应数据,可以通过getInputStream()方法读取响应数据。 7. 如果要读取服务器返回的响应状态码、响应头信息等,可以通过HttpURLConnection提供的方法来获取。 使用HttpURLConnection Post方法要注意以下几点: 1. POST请求发送的参数需要绑定在请求正文中,通过OutputStream将请求正文发送给服务器。 2. 如果需要向服务器发送一个文件,则可以使用multipart/form-data编码方式。 3. HttpsURLConnection是HttpURLConnection的子类,支持HTTPS请求。在发送HTTPS请求前需要配置SSLSocketFactory和HostnameVerifier。 总结来说,HttpURLConnection Post方法是一种比较简单易用的与服务器进行HTTP协议通信的方法,可以方便地发送POST请求并接收服务器响应。在实际开发中,如果要进行HTTP协议通信,建议选择使用HttpURLConnection Post方法。 ### 回答3: HttpURLConnection 是 Android 中的一个网络通信库,可以用来进行网络请求操作。其中,post 方法是 HttpURLConnection 中比较常用的一个方法。 post 方法的作用是向服务器提交数据。与 get 方法不同,post 方法不会将请求参数附加在 URL 中,而是将参数放在请求体中一并提交给服务器。这样设计的好处是可以避免 URL 过长,同时也可以保障数据的隐私性。 在使用 post 方法时,需要注意以下几个问题: 1. 设置请求方法:在创建 HttpURLConnection 对象之后,需要使用 setRequestMethod("POST") 方法将请求方法设置为 POST。 2. 设置请求头:在发送 post 请求之前,需要设置请求头,其中至少包含 Content-Type 和 Content-Length。Content-Type 指明请求体内容类型,微信支付时必须设置为 application/json。Content-Length 则指明请求体内容长度。 3. 设置请求体:用 OutputStream 向请求中写入需要提交的数据。 下面是一个 post 方法的示例代码: ``` URL url = new URL("http://example.com/api"); HttpURLConnection conn = (HttpURLConnection) url.openConnection(); conn.setRequestMethod("POST"); conn.setRequestProperty("Content-Type", "application/json"); conn.setRequestProperty("Content-Length", String.valueOf(postData.length())); OutputStream os = conn.getOutputStream(); os.write(postData.getBytes(StandardCharsets.UTF_8)); os.flush(); os.close(); int responseCode = conn.getResponseCode(); ``` 其中,url 表示请求的地址,postData 是需要提交的数据。 上述代码中,创建 HttpURLConnection 对象之后,我们首先使用 setRequestMethod 方法将请求方法设置为 POST,然后设置了两个请求头,最后将请求体写入到 outputstream 中。 执行完 write 方法之后,需要调用 flush 方法和 close 方法。其中 flush 方法是为了清空 buffer 缓存,将数据真正发送出去,close 方法是为了关闭输出流。 最后,使用 getResponseCode 方法获取服务器返回的状态码。根据不同的状态码,进行相应的处理即可。 总的来说,HttpURLConnection 中的 post 方法十分简单,只需要注意请求头和请求体的设置即可。在实际开发中,post 方法通常用于向服务器提交表单数据、文件上传、支付等一系列操作。
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值