我尝试使用POST请求在HttpClient中实现Multipart / Form-data。该代码可以在没有addBinaryBody行的情况下工作,但是有了它,它显示了一个简短的无法取消引用的错误。
公共类HttpClientTest {
public static void main(String[] args) throws IOException {
HttpClient httpclient = new DefaultHttpClient();
HttpPost httppost = new HttpPost("http://localhost:8080/Form/FileUploadServlet");
HttpEntity entity = MultipartEntityBuilder
.create()
.addTextBody("userName", "Sri")
.addTextBody("email", "rickroll@gmail.com")
*.addBinaryBody("fileName", new File("/Users/SL/Downloads/apache-tomcat-8.5.13/webapps/Form/"), ContentType.create("image/jpeg"), "job.jpg")*
.addTextBody("gender", "Female")
.build();
HttpPost httpPost = new HttpPost("http://localhost:8080/Form/FileUploadServlet");
httpPost.setEntity(entity);
HttpResponse response = httpclient.execute(httpPost);
HttpEntity result = response.getEntity();
// Execute HTTP Post Request
BufferedReader rd = new BufferedReader(new InputStreamReader(result.getContent()));
String line = "";
while((line = rd.readLine()) != null) {
System.out.println(line);
}
}
}