首页 > 解决方案 > mvc中的Web服务从android获取多部分数据

问题描述

我想在一个请求中向 tomcat 服务器发送多个图像。为此,我需要在 spring mvc 中编写 Web 服务以在 java spring mvc 中获取 android 的多部分实体。

下面是我的安卓代码

    public void upload() throws Exception {
    //Url of the server
    String url ="http://10.21.xxx.xxx:1010/MultiFileUpload/test";
    HttpClient client = new DefaultHttpClient();
    HttpPost post = new HttpPost(url);
    MultipartEntity mpEntity = new MultipartEntity();
    //Path of the file to be uploaded
    String filepath = "";

//Add the data to the multipart entity
    File file1 = new File(filepath);
    ContentBody cbFile1 = new FileBody(file1, "image/jpeg");
mpEntity.addPart("image", cbFile);

File file2 = new File(filepath);
    ContentBody cbFile2 = new FileBody(file2, "image/jpeg");
mpEntity.addPart("image", cbFile);

File file3 = new File(filepath);
    ContentBody cbFile3 = new FileBody(file3, "image/jpeg");
mpEntity.addPart("image", cbFile);

    mpEntity.addPart("name", new StringBody("Test", Charset.forName("UTF-8")));
    mpEntity.addPart("data", new StringBody("This is test report", Charset.forName("UTF-8")));


      post.setEntity(mpEntity);
    //Execute the post request
    HttpResponse response1 = client.execute(post);
    //Get the response from the server
    HttpEntity resEntity = response1.getEntity();
    String Response= EntityUtils.toString(resEntity);
    Log.d("Response:", Response);
    //Generate the array from the response
    JSONArray jsonarray = new JSONArray("["+Response+"]");
    JSONObject jsonobject = jsonarray.getJSONObject(0);
    //Get the result variables from response
    String result = (jsonobject.getString("result"));
    String msg = (jsonobject.getString("msg"));
    //Close the connection
    client.getConnectionManager().shutdown();
}

请帮助我使用网络服务。我面临很多麻烦

标签: androidweb-servicesspring-mvc

解决方案


下面的代码将读取 android/client 发送的图像。

@RequestMapping(value = "/test", method = RequestMethod.POST)
    public ResponseEntity < String > test(HttpServletRequest request,HttpServletResponse response) {

     byte[] imageBytes = null;

     try {
      MultipartHttpServletRequest multipartRequest = (MultipartHttpServletRequest) request;
      for (Entry < String, MultipartFile > entry: multipartRequest.getFileMap().entrySet()) {
       imageBytes = entry.getValue().getBytes();
      }
     } catch (Exception e) {
      e.printStackTrace();
     }
    }

推荐阅读