2017-09-22 2 views
0

J'ai décidé de réécrire mon ancien code parce que HttpPost, HttpResponse et HttpEntity sont maintenant obsolètes. Voici mon ancien code:Android: Envoyer le fichier au serveur avec les paramètres

private static String uploadFile(String token, File tempFile, String uploadUrl, final String fileName) 
     throws IOException, ExecutionException, InterruptedException { 

    try { 
     FileInputStream in = new FileInputStream(tempFile); 
     byte[] fileBytes = org.apache.commons.io.IOUtils.toByteArray(in); 
     in.close(); 

     MultipartEntityBuilder builder = MultipartEntityBuilder.create(); 
     builder.setMode(HttpMultipartMode.BROWSER_COMPATIBLE); 
     builder.addPart("token", new StringBody(token, ContentType.TEXT_PLAIN)); 
     builder.addPart("name", new StringBody(fileName, ContentType.TEXT_PLAIN)); 
     builder.addPart("file", new ByteArrayBody(fileBytes, fileName)); 
     builder.addPart("fileType", new StringBody("IMAGE", ContentType.TEXT_PLAIN)); 
     HttpPost postRequest = new HttpPost(uploadUrl); 
     postRequest.setEntity(builder.build()); 

     CloseableHttpClient httpClient = HttpClientBuilder.create().build(); 

     org.apache.http.HttpResponse response = httpClient.execute(postRequest); 
     int statusCode = response.getStatusLine().getStatusCode(); 

     if (statusCode == 200) { 
      HttpEntity urlEntity = response.getEntity(); 
      String str = org.apache.commons.io.IOUtils.toString(urlEntity.getContent()); 
      JsonObject jsonObject = new JsonParser().parse(str).getAsJsonObject(); 
      String Url = jsonObject.get("url").getAsString(); 
      String blobKey = jsonObject.get("key").getAsString(); 


      return Url; 

     } 
    } 
} 

Donc, maintenant je cherche une alternative. Je regarde à HttpURLConnection, mais est-il possible d'ajouter des paramètres à la demande? Je serai heureux pour toute aide ou font allusion

Répondre

2

entièrement travaillé Code

public class FileUploader { 
    private static final String LINE_FEED = "\r\n"; 
    private String boundary; 
    private HttpURLConnection httpConn; 
    private String charset = "UTF-8"; 
    private OutputStream outputStream; 
    private PrintWriter writer; 

    public String worker(String url, String params) { 
     String requestURL = url; 
     try { 
      MultipartUtility multipart = new MultipartUtility(requestURL, charset); 
      try { 
       JSONObject obj = new JSONObject(params); 
       Iterator<String> iter = obj.keys(); 
       while (iter.hasNext()) { 
        String key = iter.next(); 

        try { 
         Object value = obj.get(key); 
         Logger.e("key " + key + " value " + value.toString()); 

         multipart.addFormField("" + key, "" + value.toString()); 
        } catch (JSONException e) { 
         // Something went wrong! 
         return null; 
        } 
       } 
      } catch (JSONException e) { 
       e.printStackTrace(); 
      } 


      /* 
      if u have file add this parametr 
      */ 
      // multipart.addFilePart("photo", file); 


      List<String> response = multipart.finish(); 

      System.out.println("SERVER REPLIED:"); 
      StringBuilder sb = new StringBuilder(); 
      if (response == null) { 
       return null; 
      } 
      for (String line : response) { 
       System.out.println(line); 
       sb.append(line); 
      } 
      return sb.toString(); 
     } catch (IOException ex) { 
      System.err.println(ex); 
     } 
     return null; 
    } 

    public class MultipartUtility { 

     public MultipartUtility(String requestURL, String ch) 
       throws IOException { 
      charset = ch; 
      boundary = "===" + System.currentTimeMillis() + "==="; 

      URL url = new URL(requestURL); 
      httpConn = (HttpURLConnection) url.openConnection(); 
      httpConn.setUseCaches(false); 
      httpConn.setRequestMethod("POST"); 
      httpConn.setDoOutput(true); // indicates POST method 
      httpConn.setDoInput(true); 

      //if need autorization 
      //httpConn.setRequestProperty("Authorization", "Basic " + encoded); 

      httpConn.setRequestProperty("Content-Type", "multipart/form-data; boundary=" + boundary); 
      outputStream = httpConn.getOutputStream(); 
      writer = new PrintWriter(new OutputStreamWriter(outputStream, charset), true); 
     } 


     public void addFormField(String name, String value) { 
      writer.append("--" + boundary).append(LINE_FEED); 
      writer.append("Content-Disposition: form-data; name=\"" + name + "\"") 
        .append(LINE_FEED); 
      writer.append("Content-Type: text/plain; charset=" + charset).append(
        LINE_FEED); 
      writer.append(LINE_FEED); 
      writer.append(value).append(LINE_FEED); 
      writer.flush(); 
     } 

     public void addFilePart(String fieldName, File uploadFile) 
       throws IOException { 
      String fileName = uploadFile.getName(); 
      writer.append("--" + boundary).append(LINE_FEED); 
      writer.append(
        "Content-Disposition: form-data; name=\"" + fieldName 
          + "\"; filename=\"" + fileName + "\"") 
        .append(LINE_FEED); 
      writer.append(
        "Content-Type: " 
          + URLConnection.guessContentTypeFromName(fileName)) 
        .append(LINE_FEED); 
      writer.append("Content-Transfer-Encoding: binary").append(LINE_FEED); 
      writer.append(LINE_FEED); 
      writer.flush(); 

      FileInputStream inputStream = new FileInputStream(uploadFile); 
      byte[] buffer = new byte[4096]; 
      int bytesRead = -1; 
      while ((bytesRead = inputStream.read(buffer)) != -1) { 
       outputStream.write(buffer, 0, bytesRead); 
      } 
      outputStream.flush(); 
      inputStream.close(); 

      writer.append(LINE_FEED); 
      writer.flush(); 
     } 

     public void addHeaderField(String name, String value) { 
      writer.append(name + ": " + value).append(LINE_FEED); 
      writer.flush(); 
     } 


     public List<String> finish() throws IOException { 
      List<String> response = new ArrayList<String>(); 

      writer.append(LINE_FEED).flush(); 
      writer.append("--" + boundary + "--").append(LINE_FEED); 
      writer.close(); 

      int status = httpConn.getResponseCode(); 
      if (status == HttpURLConnection.HTTP_OK) { 
       BufferedReader reader = new BufferedReader(new InputStreamReader(
         httpConn.getInputStream())); 
       String line = null; 
       while ((line = reader.readLine()) != null) { 
        response.add(line); 
       } 
       reader.close(); 
       httpConn.disconnect(); 
      } else { 
       BufferedReader r = new BufferedReader(new InputStreamReader(httpConn.getErrorStream())); 
       StringBuilder total = new StringBuilder(); 
       String line; 
       while ((line = r.readLine()) != null) { 
        total.append(line).append('\n'); 
       } 
       Logger.e("Exception : " + total.toString()); 
       return null; 
      } 

      return response; 
     } 
    } 
} 

et comment utiliser:

FileUploader fileUploader = new FileUploader(); 
String result = fileUploader.worker(url, params) 

params - son JsonObject converti en chaîne (mJsonObject.toString()

// multipart.addFilePart ("photo", fichier);

photo = param sur le serveur (populaire son nom de fichier/fichier/photo/image)