改造无法上传多部分文件

时间:2019-04-27 02:38:45

标签: android retrofit2

我已经编写了一个代码,用于在不使用Retrofit2的情况下上传可以正常工作的文件。

此代码不使用Retrofit2

       String boundary = UUID.randomUUID().toString();

        String url = protocolName + "://" + serverInfo.getIp() + ":" + serverInfo.getPort() + httpRequest.getPath();
        try {
            URL urlObj = new URL(url);
            HttpURLConnection conn = (HttpURLConnection) urlObj.openConnection();
            conn.setReadTimeout(20000);
            conn.setConnectTimeout(20000);
            conn.setRequestMethod("POST");
            conn.setDoInput(true);
            conn.setDoOutput(true);
            String userCredentials = userInfo;
            byte[] authEncBytes = android.util.Base64.encode(userCredentials.getBytes(), android.util.Base64.NO_WRAP);
            String authStringEnc = new String(authEncBytes);
            conn.addRequestProperty("Authorization", "Basic " + authStringEnc);
            if (httpRequest.getAppInfo() != null) {
                conn.setRequestProperty("Content-Type", "multipart/form-data; boundary=" + boundary);
            }
            String fileName = httpRequest.getAppInfo().getName();
            DataOutputStream request = new DataOutputStream(conn.getOutputStream());

            if (httpRequest.getPairs() != null) {
                List<NameValuePair> params = httpRequest.getPairs();
                for (int i = 0; i < params.size(); i++) { 
                    request.writeBytes("--" + boundary + "\r\n");
                    request.writeBytes("Content-Disposition: form-data; name=\"" + params.get(i).getName() + "\"" + "\r\n");
                    request.writeBytes("Content-Type: text/plain; charset=UTF-8" + "\r\n");
                    request.writeBytes("\r\n");
                    request.writeBytes(params.get(i).getValue() + "\r\n");
                    request.writeBytes("--" + boundary + "--\r\n");
                    request.flush();    
                }
            }
            if (httpRequest.getAppInfo() != null) { 
                byte[] file = getBytes(getFile(httpRequest.getAppInfo()));
                request.writeBytes("--" + boundary + "\r\n");
                request.writeBytes("Content-Disposition: form-data; name=\"file\"; filename=\"" + fileName + "\"\r\nContent-Type: application/vnd.android.package-archive\r\n\r\n");
                request.write(file);
                request.writeBytes("\r\n");
                request.writeBytes("--" + boundary + "--\r\n");
                request.flush();
            }   
            int responseCode = conn.getResponseCode();

            if (responseCode == HttpURLConnection.HTTP_OK) {
                InputStream inputStream = conn.getInputStream();
                BufferedReader in = new BufferedReader(new InputStreamReader(inputStream));
                StringBuffer sb = new StringBuffer("");
                String line;
                while ((line = in.readLine()) != null) {
                    sb.append(line);
                }
                in.close();
                conn.disconnect();
                return sb.toString();

            } else if (responseCode == 400) {
                InputStream inputStream;
                inputStream = conn.getErrorStream();

                BufferedReader reader = new BufferedReader(new InputStreamReader(inputStream));
                String line;
                StringBuffer buffer = new StringBuffer("");
                while ((line = reader.readLine()) != null) {
                    buffer.append(line);
                }

                reader.close();
                conn.disconnect();
                return buffer.toString();

            } else {
                return String.valueOf(responseCode) + " httpresponse error code";
          ...

但是当我想使用Retrofit时,程序返回200代码,但是上传的文件未存储在服务器上:

这是我使用Retrofit 的代码;

        @Multipart
        @POST("/api/device/{token}/upload/{hash}/{version}/{name}")
        Call<ResponseBody> uploadFile(@Part MultipartBody.Part file,
                                      @Path("token") String token,
                                      @Path("hash") String hash,
                                      @Path("version") String version,
                                      @Path("name") String name);

,主要类别是:

                File file = new File(UtilsApp.getAppFolder().getPath() + "/" +
                        UtilsApp.getAPKFilename(appInfo) + ".apk");
                ProgressRequestBody fileBody = new ProgressRequestBody(file, "multipart/form-data", this);
                MultipartBody.Part filePart = MultipartBody.Part.createFormData("file", file.getName(), fileBody);
                UploadAPI uploadAPI =
                        ServiceGenerator.createService(UploadAPI.class, "user", "pass");

                Call<ResponseBody> request = uploadAPI.uploadFile(filePart,
                        token, appInfo.getHash(),
                        appInfo.getVersion(),
                        appInfo.getName()); 
                request.enqueue(new Callback<ResponseBody>() {
                    @Override
                    public void onResponse(Call<ResponseBody> call, Response<ResponseBody> response) {
                        if (response.isSuccessful()) {
                            Log.e(">> Success", "Code: 200");
                        }                                                    }

                    @Override
                    public void onFailure(Call<ResponseBody> call, Throwable t) {
                                         Log.e(">> Fail: ", "Failure: "+ t.getMessage());
                    }
                });

哪里有问题? 感谢您分享您的知识。

0 个答案:

没有答案