有以下代码:
private static String doPostRequest(List<NameValuePair> params, String url) throws ClientProtocolException, IOException {
HttpClient httpclient = new DefaultHttpClient();
HttpPost httppost = new HttpPost(url);
httppost.setEntity(new UrlEncodedFormEntity(params, "UTF-8"));
HttpResponse response = httpclient.execute(httppost);
return getContentFromInputStream(response.getEntity().getContent());
}
private static String getContentFromInputStream(InputStream is) throws IOException {
String line;
StringBuilder sb=new StringBuilder();
BufferedReader reader=new BufferedReader(new InputStreamReader(is));
while((line=reader.readLine())!=null) {
sb.append(line);
}
reader.close();
return sb.toString();
}
那么,如何在POST请求中添加一些图像(例如File f)?提前致谢。
答案 0 :(得分:1)
这是Servlet 3的“多部分文件上传”的一部分。
您将构建映像的blob,然后将其发布到Servlet 3端点。
如果您计划使用Spring,那么有一些非常好的简单注释来定义您的控制器,它们可以与文件上传一起使用,您可以看到here
答案 1 :(得分:0)
您可以使用MultipartRequestEntity。
File f = new File(filePath);
PostMethod postMessage = new PostMethod(urlString);
Part[] parts = {
new StringPart("param", "value"),
new FilePart(f.getName(), f)
};
postMessage.setRequestEntity(new MultipartRequestEntity(parts, postMessage.getParams()));
HttpClient client = new HttpClient();
int status = client.executeMethod(postMessage);