2017-09-22 100 views
0

我決定重寫我的舊代碼,因爲現在HttpPost,HttpResponse和HttpEntity已被棄用。這是我的舊代碼:Android:發送文件到服務器的參數

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; 

     } 
    } 
} 

所以,現在我正在尋找一些替代方案。我期待HttpURLConnection,但是有什麼辦法可以添加參數來請求嗎? 我會很高興的任何幫助或暗示

回答

2

完全工作代碼

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; 
     } 
    } 
} 

以及如何使用:

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

PARAMS - 它的JSONObject轉換成字符串(mJsonObject.toString() )

// multipart.addFilePart(「photo」,file);

photo =服務器上的參數(流行其文件名/文件/照片/圖像)

相關問題