用PostMethod 模擬http post請求,需要解決傳遞字符串,文件等需求。
httpclient對此,提供了對應(yīng)實(shí)現(xiàn),實(shí)現(xiàn)方法關(guān)鍵在:RequestEntity。
示例:
RequestEntity requestEntity = newStringRequestEntity(text);
post.setRequestEntity(requestEntity);
示例中,是傳遞一個(gè)普通字符型參數(shù)。
這個(gè)方法代替了以前直接設(shè)置Request body。
RequestEntity是一個(gè)接口,有很多實(shí)現(xiàn):
ByteArrayRequestEntity, FileRequestEntity, InputStreamRequestEntity, MultipartRequestEntity, StringRequestEntity
基本上從名字上就可以直接看出功能,可以從字符串,流,文件,字節(jié)數(shù)組中產(chǎn)生request body。
還有更復(fù)雜的Multipart,就是夾雜文件和普通字段的提交。
示例如下:
Part[] parts = {new StringPart("source", "695132533"), new StringPart("status", URLEncoder.encode(status, "utf-8")), filePart};
postMethod.setRequestEntity(new MultipartRequestEntity(parts, postMethod.getParams()));