如何在POST请求Java中添加图像?
有以下代码:如何在POST请求Java中添加图像?,java,Java,有以下代码: private static String doPostRequest(List<NameValuePair> params, String url) throws ClientProtocolException, IOException { HttpClient httpclient = new DefaultHttpClient(); HttpPost httppost = new HttpPost(url); httppost.setEn
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();
}
私有静态字符串doPostRequest(列表参数,字符串url)抛出ClientProtocolException,IOException{
HttpClient HttpClient=新的DefaultHttpClient();
HttpPost HttpPost=新的HttpPost(url);
setEntity(新的UrlEncodedFormEntity(参数,“UTF-8”);
HttpResponse response=httpclient.execute(httppost);
返回getContentFromInputStream(response.getEntity().getContent());
}
私有静态字符串getContentFromInputStream(InputStream为)引发IOException{
弦线;
StringBuilder sb=新的StringBuilder();
BufferedReader reader=新的BufferedReader(新的InputStreamReader(is));
而((line=reader.readLine())!=null){
某人附加(行);
}
reader.close();
使某人返回字符串();
}
那么,如何将一些图像(例如文件f)添加到POST请求中?提前谢谢 这是Servlet 3“多部分文件上传”的一部分 您将构建一个图像blob,然后将其发布到Servlet3端点 请看一下示例和示例 如果您计划使用Spring,那么它有一些非常好的简单注释来定义您的控制器,这些控制器将与文件上载一起工作,您可以看到您可以使用的
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);