最近做http协议下面的数据传输,总结一下
1. 上传单个文件:
服务器端代码:
@RequestMapping(value = "/POST", method = RequestMethod.POST)
@ResponseBody
public String PostTest(String test_data, MultipartFile file ){
System. out.println("comming here!" );
if (!file .isEmpty()) {
try {
byte[] bytes = file .getBytes();
BufferedOutputStream stream = new BufferedOutputStream(
new FileOutputStream(new File("d:\temp\" + test_data + "-uploaded")));
stream.write( bytes);
stream.close();
return "You successfully uploaded " + test_data + " into " + test_data + "-uploaded !" ;
} catch (Exception e ) {
return "You failed to upload " + test_data + " => " + e.getMessage();
}
} else {
return "You failed to upload " + test_data + " because the file was empty.";
}
}
客户端代码:
public static void testUploadOne() throws ClientProtocolException, IOException{
@SuppressWarnings("resource" )
HttpClient httpclient = new DefaultHttpClient() ;
HttpPost httppost = new HttpPost("http://127.0.0.1:8080/POST/" );
FileBody fileContent = new FileBody(new File( "D:\projectSet.psf"));
StringBody stringBody = new StringBody ("123456" );
@SuppressWarnings("deprecation" )
MultipartEntity reqEntity = new MultipartEntity();
reqEntity.addPart("file", fileContent);
reqEntity.addPart("test_data", stringBody );
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();
}
}
2.
一次上传多个文件:
服务器端代码:
public static String writeMulti(String test_data , MultipartFile file){
if (!file .isEmpty()) {
try {
byte[] bytes = file .getBytes ();
BufferedOutputStream stream = new BufferedOutputStream(
new FileOutputStream( new File("d:\temp\" + test_data)));
stream. write(bytes);
stream. close();
return "You successfully uploaded " + test_data + " into " + test_data + "!" ;
} catch (Exception e) {
return "You failed to upload " + test_data + " => " + e.getMessage();
}
} else {
return "You failed to upload " + test_data + " because the file was empty.";
}
}
@RequestMapping(value = "/TPOST", method = RequestMethod.POST)
@ResponseBody
public void Test(@RequestParam ("file_name" ) String[] file_name, @RequestParam("file" ) MultipartFile[] file,
HttpServletRequest request) throws FileUploadException, IOException{
System. out.println("comming here!" );
System. out.println("file name length: " + file_name .length + " file length: " + file.length);
writeMulti(file_name [0], file [0]);
writeMulti(file_name [1], file [1]);
}
客户端代码:
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!!" );
}