研究着上傳視頻到企鵝號的接口,而騰訊內容開放開發者平台的接口調用請求說明是:
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" />