Java客户端通过Http发送POST请求上传文件到web服务器

通过HttpURLConnection类实现http协议上传信息

import java.io.BufferedInputStream;
import java.io.BufferedWriter;
import java.io.ByteArrayOutputStream;
import java.io.InputStream;
import java.io.OutputStreamWriter;
import java.net.HttpURLConnection;
import java.net.URL;

import com.sys.common.log.Log;

/**
 * 
 */

/**
 * 使用HttpURLConnection对象模拟测试后台接口
 * @author
 *
 */
public class MyHttpURLConnection {
	
	private static String HTTP_URL="http://www.baidu.com";
	private static String	HTTP_METHOD_POST="POST";
	
	
	
	public static void main(String[] args) {
		
		 
		 try {
		System.out.println(	MyHttpURLConnection.sendHttp(""));
		} catch (Exception e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
	}
	
	
	
	
	
	/**
	 * 模拟HTTP 请求 提交普通数据
	 * 
	 * @param postData
	 *            发送数据
	 * @return
	 */
	private static String sendHttp(String postData) throws Exception {
		if (HTTP_URL == null || "".equals(HTTP_URL)) {
			throw new Exception("请传入远程请求地址");
		}
		String result = "";
		BufferedWriter out = null;
		BufferedInputStream reader = null;
		HttpURLConnection connection = null;
		try {
			URL u = new URL(HTTP_URL);
			connection = (HttpURLConnection) u.openConnection();
			int code;
			connection.setDoOutput(true);//是否向connection输出  
			connection.setUseCaches(false);//因为是post请求所以不能使用缓存
			connection.setConnectTimeout(120000); // 连接超时为120秒
			connection.setRequestMethod(HTTP_METHOD_POST);
			//告诉服务端 要发送数据的长度
			connection.setRequestProperty("Content-Length",
					postData.getBytes("UTF-8").length + "");
			//告诉服务器客户端浏览器内核
			connection.setRequestProperty("User-Agent", "Mozilla/4.0");
			//告诉服务器 要发送数据的格式和字符编码
			connection.setRequestProperty("Content-Type",
					"text/xml;charset=UTF-8");
			//通过connection连接对象获取输出流对象
			out = new BufferedWriter(new OutputStreamWriter(
					connection.getOutputStream(), "UTF-8"));
			//将需要想客户端发送的信息写入到输出流  刷新输出流并且关闭流
			out.write(postData);
			out.flush();
			out.close();
			out = null;
			code = connection.getResponseCode();
			if (code == HttpURLConnection.HTTP_OK) {
				ByteArrayOutputStream byteArrayOutputStream = new ByteArrayOutputStream();
				reader = new BufferedInputStream(connection.getInputStream());
				int b;
				byte[] bit = new byte[1024];
				while (-1 != (b = reader.read(bit))) {
					byteArrayOutputStream.write(bit, 0, b);
				}
				result = new String(byteArrayOutputStream.toByteArray());
			} else {
				Log.error("post ResponseCode=" + connection.getResponseCode());
				Log.error("post ResponseMessage="
						+ connection.getResponseMessage());
				reader = new BufferedInputStream(connection.getErrorStream());
				ByteArrayOutputStream byteArrayOutputStream = new ByteArrayOutputStream();
				int b;
				byte[] bit = new byte[1024];
				while (-1 != (b = reader.read(bit))) {
					byteArrayOutputStream.write(bit, 0, b);
				}
				result = new String(byteArrayOutputStream.toByteArray());
				throw new Exception("服务端发生异常");
			}
		} catch (Exception e) {
			e.printStackTrace();
			throw e;
		} finally {
			if (out != null) {
				out.flush();
				out.close();
			}
			if (reader != null) {
				reader.close();
			}
			if (connection != null) {
				connection.disconnect();
			}
		}
		return result;
	}

}


  • 1
    点赞
  • 7
    收藏
    觉得还不错? 一键收藏
  • 1
    评论
Java 中,可以使用 Servlet 来实现文件客户,具体步骤如下: 1. 创建一个 HTML 表单,用于上文件。表单中可以包含一个文件选择框和一个提交按钮。 ``` <form action="/upload" method="post" enctype="multipart/form-data"> <input type="file" name="file"> <input type="submit" value="Upload"> </form> ``` 2. 创建一个 Servlet 类,在其中处理文件请求。在 Servlet 中,需要使用 `HttpServletRequest` 对象获取上文件,然后将文件写入到 `HttpServletResponse` 对象中,以便客户可以下载该文件。 ``` @WebServlet("/upload") @MultipartConfig public class FileUploadServlet extends HttpServlet { protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { Part filePart = request.getPart("file"); InputStream inputStream = filePart.getInputStream(); OutputStream outputStream = response.getOutputStream(); response.setContentType("application/octet-stream"); response.setHeader("Content-Disposition", "attachment; filename=\"" + filePart.getSubmittedFileName() + "\""); byte[] buffer = new byte[1024]; int bytesRead; while ((bytesRead = inputStream.read(buffer)) != -1) { outputStream.write(buffer, 0, bytesRead); } outputStream.flush(); outputStream.close(); inputStream.close(); } } ``` 上述代码中,`@MultipartConfig` 注解用于指示该 Servlet 接受多部分请求(即包含文件)。 3. 部署应用程序并启动 Web 服务器。 当用户在浏览器中打开上文件的 HTML 表单并选择要上文件后,客户会将文件Web 服务器Web 服务器会将请求发送到 FileUploadServlet,该 Servlet 会将文件写入到 `HttpServletResponse` 中并发送客户客户就可以下载该文件了。

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值