首页 > 解决方案 > 即使我输入错误的密码并且文件未保存在服务器上,我也总是得到 Server Response ok 200

问题描述

我正在使用我的 Android APP 中的 Java 类将文件上传到我的服务器。我正在使用一个简单的 php Skript 来检查密码。如果我输入错误的密码,文件不会保存在服务器上,我应该得到 403,但我从服务器得到 OK 200。

这是Java类

class httpUploadFile {
    private int serverResponseCode = 0;
     int uploadFile(String upLoadServerUri, String uploadFilePath, String uploadFileName,String pfad) {
            String sourceFileUri=uploadFilePath + "" + uploadFileName;
         HttpURLConnection conn;
            DataOutputStream dos;
            String lineEnd = "\r\n";
            String twoHyphens = "--";
            String boundary = "*****";
            int bytesRead, bytesAvailable, bufferSize;
            byte[] buffer;
            int maxBufferSize = 1024 * 1024;
            File sourceFile = new File(sourceFileUri);
         if (!sourceFile.isFile()) {
             Log.e("uploadFile", "Source File not exist :"
                     +uploadFilePath + "" + uploadFileName);
             return 0;
         }
            try {
                FileInputStream fileInputStream = new FileInputStream(sourceFile);
                String fulluri=getUrl(upLoadServerUri,pfad);
                URL url = new URL(fulluri);
                conn = (HttpURLConnection) url.openConnection();
                conn.setDoInput(true); // Allow Inputs
                conn.setDoOutput(true); // Allow Outputs
                conn.setUseCaches(false); // Don't use a Cached Copy
                conn.setRequestMethod("POST");
                conn.setRequestProperty("Connection", "Keep-Alive");
                conn.setRequestProperty("ENCTYPE", "multipart/form-data");
                conn.setRequestProperty("Content-Type", "multipart/form-data;boundary=" + boundary);
                conn.setRequestProperty("uploaded_file", sourceFileUri);
                dos = new DataOutputStream(conn.getOutputStream());
                dos.writeBytes(twoHyphens + boundary + lineEnd);
                dos.writeBytes("Content-Disposition: form-data; name=\"uploaded_file\";filename=\""
                                + sourceFileUri + "\"" + lineEnd);
                        dos.writeBytes(lineEnd);
                // create a buffer of  maximum size
                bytesAvailable = fileInputStream.available();
                bufferSize = Math.min(bytesAvailable, maxBufferSize);
                buffer = new byte[bufferSize];
                // read file and write it into form...
                bytesRead = fileInputStream.read(buffer, 0, bufferSize);
                while (bytesRead > 0) {
                    dos.write(buffer, 0, bufferSize);
                    bytesAvailable = fileInputStream.available();
                    bufferSize = Math.min(bytesAvailable, maxBufferSize);
                    bytesRead = fileInputStream.read(buffer, 0, bufferSize);
                }
                // send multipart form data necesssary after file data...
                dos.writeBytes(lineEnd);
                dos.writeBytes(twoHyphens + boundary + twoHyphens + lineEnd);
                // Responses from the server (code and message)
                serverResponseCode = conn.getResponseCode();
                String serverResponseMessage = conn.getResponseMessage();
                Log.i("uploadFile", "HTTP Response is : "
                        + serverResponseMessage + ": " + serverResponseCode);
                fileInputStream.close();
                dos.flush();
                dos.close();
            } catch (MalformedURLException ex) {

                ex.printStackTrace();

                  Log.e("Upload file to server", "error: " + ex.getMessage(), ex);
            } catch (Exception e) {

                e.printStackTrace();

                Log.e("Upload file Exception", "Exception : "
                        + e.getMessage(), e);
            }

            return serverResponseCode;
        }
    private String getUrl(String BASE_URL,String pfad) {
        String token = getToken();
        String key = getKey(token);
        return String.format("%s?token=%s&key=%s&pfad=%s&", BASE_URL, token, key,pfad);
    }

    private String getKey(String token) {
        return md5(String.format("%s+%s", "wrongpassword", token));
    }

    private String getToken() {
        return md5(UUID.randomUUID().toString());
    }

    private static String md5(String s) {
        MessageDigest m = null;
        try {
            m = MessageDigest.getInstance("MD5");
        } catch (NoSuchAlgorithmException e) {
            e.printStackTrace();
        }
        assert m != null;
        m.update(s.getBytes(), 0, s.length());
        return new BigInteger(1, m.digest()).toString(16);
    }
    }

这是PHP

<?php
$shared_secret = "password";    
$key = $_GET['key'];    
$token = $_GET['token'];    
$pfad = $_GET['pfad'];    
if ($key != hash("md5", "{$shared_secret}+{$token}")) {    
  header('HTTP/1.0 403 Forbidden');    
  die('403 Forbidden: You are not allowed to access this file.');
}    
$file_path = "/home/www/data/".$pfad."/";
$file_path = $file_path . basename( $_FILES['uploaded_file']['name']);
if(move_uploaded_file($_FILES['uploaded_file']['tmp_name'], $file_path)) {
    echo "success";
} else {
    echo "fail";
}
?>

标签: javaphpandroidhttp-upload

解决方案


HTTP200表示 HTTP 层面的传输是 OK 的,也就是说,请求在技术上是 OK的,服务​​器能够正确响应。

200不判断你的业务逻辑是真是假,所以即使密码错误,只有服务器和客户端的http通信正常,才会返回200 。

通常,如果服务器上发生技术或不可恢复的问题,我们会使用 HTTP 5xx进行响应。或者 HTTP 4xx如果传入的请求有问题(例如错误的参数)

你的后端服务器应该做上面的判断。


推荐阅读