模拟表单方式上传文件


研究着上传视频到企鹅号的接口,而腾讯内容开放开发者平台的接口调用请求说明是:

http请求方式: POST/FORM

调用示例(使用curl命令,用FORM表单方式上传一个多媒体文件):

curl -F "media=@test.wmv" "http://api.om.qq.com/article/clientpubvid?access_token=ACCESS_TOKEN&

title=TITLE&tags=TAGS&cat=CATmd5=MD5&desc=DESC"

 

换一种方式  用MultipartRequestEntity 替换 RequestEntity,

而RequestEntity是一个接口,有很多实现:ByteArrayRequestEntity, FileRequestEntity, InputStreamRequestEntity, StringRequestEntity, MultipartRequestEntity,他们分别指可以从字节数组,文件,流,字符串中产生request body。还有更复杂的Multipart,就是夹杂文件和普通字段的提交。

 

我的运行源码如下,url需要带参数的url,

import java.io.File;
import java.io.FileNotFoundException;
import java.io.IOException;

import org.apache.commons.httpclient.HttpClient;
import org.apache.commons.httpclient.HttpException;
import org.apache.commons.httpclient.methods.PostMethod;
import org.apache.commons.httpclient.methods.multipart.FilePart;
import org.apache.commons.httpclient.methods.multipart.MultipartRequestEntity;
import org.apache.commons.httpclient.methods.multipart.Part;
import org.apache.commons.httpclient.params.HttpMethodParams;

public class MyHttpClient {
	public static void main(String[] args) throws HttpException, IOException {
		HttpClient client = new HttpClient();  
		PostMethod post = new PostMethod("url");
		FilePart fp;
		try {
			fp = new FilePart("formFile", new File("E:\\123.text"));
			Part[] parts = {fp};
			MultipartRequestEntity entity = new MultipartRequestEntity(parts, new HttpMethodParams());
			post.setRequestEntity(entity); 
			client.executeMethod(post);  
			String result= post.getResponseBodyAsString();//释放连接,以免超过服务器负荷 post.releaseConnection();
			System.out.println(result);//返回
		} catch (FileNotFoundException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		
	}
}

  

再解释一下 

post.setRequestEntity(new MultipartRequestEntity(parts,new HttpMethodParams())); 
设置多媒体参数,作用类似form表单中的enctype="multipart/form-data" ,

 

Part[] parts = { new FilePart("filename", f) };

设定参数名称和值,类似form表单中的<input name="filename” type="file" /> 

  

 


免责声明!

本站转载的文章为个人学习借鉴使用,本站对版权不负任何法律责任。如果侵犯了您的隐私权益,请联系本站邮箱yoyou2525@163.com删除。



 
粤ICP备18138465号  © 2018-2025 CODEPRJ.COM