用URL请求做文件上传
2011-11-19 17:43
232 查看
JAVA可以用URL请求直接发送HTTP请求,和web server交互,就和浏览器一样。发送的内容格式是:
假设传的文件名是test.txt,内容是:
代码概要如下:
假设传的文件名是test.txt,内容是:
content of test.txt
-----------------------------7d65d38307d2 Content-Disposition: form-data; name="myfile"; filename="E:\badboy\test.txt" Content-Type: text/plain content of test.txt -----------------------------7d65d38307d2--
代码概要如下:
URL url = new URL(requestUrl); HttpURLConnection conn = (HttpURLConnection) url.openConnection(); conn.setRequestMethod("POST"); conn.setDoOutput(true); //perform just like browser does when uploading files, using multipart/form-data StringBuffer sb = new StringBuffer(); sb.append("--"); sb.append(CommonUtil.BOUNDRAY); sb.append("\r\n"); sb.append("Content-Disposition: form-data; name=\"pictureInfo.file\"; filename=\"" + picFileName + "\"\r\n"); sb.append("Content-Type: application/octet-stream\r\n\r\n"); byte[] start_data = sb.toString().getBytes(); byte[] end_data = ("\r\n--" + CommonUtil.BOUNDRAY + "--\r\n").getBytes(); conn.setRequestProperty("Content-Type", "multipart/form-data; boundary=" + CommonUtil.BOUNDRAY); conn.setRequestProperty("Content-Length", String.valueOf(start_data.length + pic_data.length + end_data.length)); //设置内容长度 conn.setConnectTimeout(CommonUtil.NETWORK_TIME_OUT); BufferedOutputStream bos = new BufferedOutputStream(conn.getOutputStream()); bos.write(start_data); bos.write(pic_data); bos.write(end_data); bos.flush(); bos.close(); conn.connect();
相关文章推荐
- 利用HttpURLConnection发送post请求上传多个文件
- 使用HttpURLConnection通过POST方式提交请求数据,并上传文件
- 利用HttpURLConnection发送post请求上传文件
- HttpURLConnection_Get和Post请求文件上传
- 使用HttpUrlConnection进行post请求上传文件
- 使用HttpUrlConnection进行post请求上传文件
- 利用HttpURLConnection发送post请求上传多个文件
- 利用HttpURLConnection发送post请求上传文件
- Java模拟http上传文件请求(HttpURLConnection,HttpClient4.4,RestTemplate)
- Java利用HttpURLConnection发送post请求上传文件
- HTTP文件上传请求格式详解,利用HttpURLConnection上传文件
- Java利用HttpURLConnection发送post请求上传文件
- 利用HttpURLConnection发送post请求上传文件
- 利用HttpURLConnection发送post请求上传多个文件
- 获取请求URL、Cookie及文件上传处理
- 使用HttpURlConnection 发送POST请求上传文件(带参数)
- 利用HttpURLConnection发送post请求上传多个文件
- 使用HttpUrlConnection进行post请求上传文件
- Http请求之基于HttpUrlConnection,支持Header,Body传值,支持Multipart上传文件:
- 利用HttpURLConnection发送post请求上传多个文件