下面demo是使用MultipartEntity上传图片,服务器端代码暂不提供
注意MultipartEntity需要使用Httpmine.jar
String BOUNDARY = "--"+UUID.randomUUID().toString();
MultipartEntity multipartEntity = new MultipartEntity(HttpMultipartMode.BROWSER_COMPATIBLE,BOUNDARY, Charset.forName(CHARSET));
multipartEntity.addPart("file",new FileBody(new File(filePath)));
String requestURL=Constant.FAKE_UPLOADING_RESPONSE;
HttpPost request = new HttpPost(requestURL);
request.setEntity(multipartEntity);
request.addHeader("Content-Type","multipart/form-data;boundary="+BOUNDARY);
DefaultHttpClient httpClient = new DefaultHttpClient();
HttpResponse response;
try {
response = httpClient.execute(request);
InputStream is = response.getEntity().getContent();
BufferedReader in = new BufferedReader(new InputStreamReader(is));
StringBuffer buffer = new StringBuffer();
String line = "";
while ((line = in.readLine()) != null) {
buffer.append(line);
}
String result=buffer.toString();
return result;
} catch (ClientProtocolException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
在Server端,可以使用表单模拟,那么约定的input element中的值对应addPart部分的“file“值
以上