public static void testUploadMultiFiles() throws ClientProtocolException, IOException{
@SuppressWarnings("resource" )
HttpClient httpclient = new DefaultHttpClient();
HttpPost httppost = new HttpPost("http://127.0.0.1:8080/TPOST/" );
FileBody fileContent = new FileBody(new File("C:\\Users\\Tangyun\\Desktop\\xiazai\\lbfs.pdf" ));
FileBody fileContent1 = new FileBody(new File("C:\\Users\\Tangyun\\Desktop\\xiazai\\server_demo.erl" ));
StringBody stringBody = new StringBody ("lbfs.pdf" );
StringBody stringBody1 = new StringBody ("server_demo.erl" );
MultipartEntity reqEntity = new MultipartEntity();
// 你只传了一个参数 test_data 没有file , 而且test_data给的值是 文件
reqEntity.addPart("file" , fileContent );
reqEntity.addPart("file_name" , stringBody );
reqEntity.addPart("file" , fileContent1 );
reqEntity.addPart("file_name" , stringBody1 );
httppost.setEntity( reqEntity);
try {
HttpResponse response = httpclient.execute(httppost );
int statusCode = response .getStatusLine().getStatusCode();
if(statusCode == HttpStatus.SC_OK){
System. out.println("服务器正常响应....." );
HttpEntity resEntity = response .getEntity();
System.out.println(EntityUtils.toString(resEntity ));// httpclient自带的工具类读取返回数据
System. out.println(resEntity .getContent());
EntityUtils. consume(resEntity);
}
} catch (ClientProtocolException e ) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IOException e ) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
3.
下载文件:
服务器端代码:
@RequestMapping(value = "/download", method = RequestMethod.GET)
public static ResponseEntity<byte[]> downloadFile(String fileId) {
HttpHeaders headers = new HttpHeaders();
headers.setContentType(MediaType. APPLICATION_OCTET_STREAM);
headers.setContentDispositionFormData( "attachment", "dict.txt" );
String downloadDataString = "download success!" ;
return new ResponseEntity<byte[]>( downloadDataString.getBytes(),
headers, HttpStatus. CREATED);
}
客户端代码:
public static void download() {
HttpClient client = new DefaultHttpClient();
HttpGet httpGet = new HttpGet("http://127.0.0.1:8080/download/" );
try {
HttpResponse response = client.execute( httpGet);
HttpEntity entity = response.getEntity();
InputStream in = entity.getContent();
FileOutputStream out = new FileOutputStream(new File("D:\\temp\\download.txt" ));
byte[] b = new byte[1000];
int len = 0;
while((len =in .read(b ))!= -1){
out.write( b,0, len);
}
in.close();
out.close();
} catch (IOException e ) {
e.printStackTrace();
} finally{
httpGet.releaseConnection();
}
System. out.println("download, success!!" );
}