今天学习使用了HttpClient4.2向服务端发送上传文件的post请求,由于服务器端采用MultipartFile形式接收,查询资料后决定使用HttpClient4.2实现,以下是实现代码(仅作测试使用):
public void testtaskPost()throws Exception{ HttpClient httpclient = new DefaultHttpClient(); try { //新建一个httpclient Post 请求 HttpPost httppost = new HttpPost("http://127.0.0.1:8889/taskmanagement/task"); //由于只是测试使用 这里的路径对应本地文件的物理路径 FileBody bin = new FileBody(new File("E://2017//1.doc")); File myfile = new File("E://2017//1.doc"); long size = myfile.length(); //向MultipartEntity添加必要的数据 StringBody comment = new StringBody("1.doc", Charset.forName("UTF-8")); MultipartEntity reqEntity = new MultipartEntity(); reqEntity.addPart("file",bin);//file为请求后台的Fileupload参数 reqEntity.addPart("filename",comment);//请求后台Fileupload的参数 httppost.setEntity(reqEntity); //这里是后台接收文件的接口需要的参数,根据接口文档需要放在http请求的请求头 String taskid ="919894d9-ea5a-4f6a-8edd-b14ef3b6f104"; httppost.setHeader("task-id",taskid); String fileid = UUID.randomUUID().toString(); httppost.setHeader("file-id",fileid); httppost.setHeader("file-name","1.doc"); httppost.setHeader("file-size",String.valueOf(size)); httppost.setHeader("total", String.valueOf(1)); httppost.setHeader("index",String.valueOf(1)); 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( //httpclient自带的工具类读取返回数据 EntityUtils.toString(resEntity)); System.out.println( resEntity.getContent()); EntityUtils.consume( resEntity); } } catch (ParseException e) { e.printStackTrace(); } catch (IOException e) { e.printStackTrace(); } finally { try { httpclient.getConnectionManager().shutdown(); } catch (Exception ignore) { } } }此段代码所需依赖包下载地址(免积分的):http://download.csdn.net/detail/coding13/9772027
新闻热点
疑难解答