您的位置:首页 > 其它

利用接口发送文件

2016-07-12 17:59 295 查看
//向平台发送图片

  public static void main(String[] args) throws Exception{

  String response="";

  PostMethod postMethod = new PostMethod("http://172.16.2.79:8080/zdxqcg/api/workflow/file");

  HttpClient client = new HttpClient();

  String fileuuid = UuidUtil.get32UUID();

  try {
  FilePart fp = new FilePart("file",new File("C:/tomcat/apache-tomcat-7.0.54/webapps/ROOT/uploadFiles/uploadImgs/20160712/1468296128108.jpg"));

fp.setCharSet("utf-8");             

fp.setContentType("image/*");              //图片格式

  //StringPart:普通文本参数

  StringPart idPart = new StringPart("fileuuid",fileuuid);

  Part[] parts = {idPart,fp};

  //HttpClient使用MultipartRequestEntity包装

  MultipartRequestEntity mre = new MultipartRequestEntity(parts,postMethod.getParams());

  postMethod.setRequestEntity(mre);

  //由于要上传的文件可能比较大,因此在此设置最大的连接超时时间

  client.getHttpConnectionManager().getParams().setConnectionTimeout(5000);

  int status = client.executeMethod(postMethod);

 

  System.out.println(status);

  System.out.println("提交成功");

  if(status ==HttpStatus.SC_OK){

  InputStream inputStream = postMethod.getResponseBodyAsStream();

  BufferedReader br = new  BufferedReader(new InputStreamReader(inputStream));

  StringBuffer stringBuffer =new StringBuffer();

  String str ="";

  while ((str = br.readLine())!=null){

  stringBuffer.append(str);

  }

  response = stringBuffer.toString();

  }else{

  response = "fail";

  }

  System.out.println(response);

  } catch (FileNotFoundException e) {

  e.printStackTrace();

  }

  }
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签:  接口传递文件