Android HttpUrlConnection网络代码受移动网络提供商的影响

时间:2016-01-18 03:44:29

标签: java android mobile android-volley httpurlconnection

我怀疑我的移动网络提供商正在影响我的代码在我的设备上运行的方式。

最初,我编写了Google排球码,将个人资料图片发送到服务器,并附上图片所有者的详细信息。

此代码已经无缝工作了很长时间,直到我在LG Optimus G Pro上运行它并发现它对于大图像安静地失败。没有例外或错误。它适用于小图像(约94KB或更少)

我在三星Galaxy S5上测试了代码,它适用于大图像和小图像。然后我开始怀疑凌空代码在这种情况下看起来没有正当理由。

所以我将代码移植到HttpUrlConnection并使用我在下面创建的类HttpUploader

令我恐惧的是,我得到的结果和凌空一样。

但是,我现在注意到,当它失败时,服务器仍会返回响应代码200,并且写入图像字节的循环仍然完成。

接下来的嫌疑人是网络提供商,比如 ETS

我使用MTN尼日利亚将违规设备连接到Galaxy S5的无线热点,这次,代码运行良好。

我现在使用 ETS 将Galaxy S5连接到LG Optimus Pro的无线热点,并且看到同样的问题发生在Galaxy S5上。

所以我确认我怀疑 ETS 网络是在窃听代码。

这是HttpUrlConnection代码:

import java.io.DataOutputStream;
import java.io.File;
import java.io.FileInputStream;
import java.net.HttpURLConnection;
import java.net.URL;

/**
 * Created by hp on 1/18/2016.
 */
public abstract class HttpUploader {

    /**
     * This is important for uploading multipart data containing a large file.
     * @param serverUrl The server url
     * @param f The file to be uploaded
     * @param params The parameters of text data to be uploaded
     * @param values The values of text  data to be uploaded
     * @return the server's response
     */
    public void uploadStuff(final String serverUrl,final int retries,final File f,final String[]params,final String...values){
   new Thread(new Runnable() {
       @Override
       public void run() {
onPreStart();

        if( params==null || values==null || serverUrl==null || params.length!=values.length){
            return;
        }
        String response = "error";
        HttpURLConnection connection = null;
        DataOutputStream outputStream = null;

        String urlServer = serverUrl;
        String lineEnd = "\r\n";
        String twoHyphens = "--";
        String boundary = "*****";

        int bytesRead, bytesAvailable, bufferSize;
        byte[] buffer;
        int maxBufferSize = 1 * 1024;
        try {
            FileInputStream fileInputStream = new FileInputStream( f );

            URL url = new URL(urlServer);
            connection = (HttpURLConnection) url.openConnection();

            // Allow Inputs & Outputs
            connection.setDoInput(true);
            connection.setDoOutput(true);
            connection.setUseCaches(false);
            connection.setChunkedStreamingMode(maxBufferSize);
            // Enable POST method
            connection.setRequestMethod("POST");

            connection.setRequestProperty("Connection", "Keep-Alive");
            connection.setRequestProperty("Content-Type",
                    "multipart/form-data; boundary=" + boundary);

            outputStream = new DataOutputStream(connection.getOutputStream());
            outputStream.writeBytes(twoHyphens + boundary + lineEnd);

            for(int i=0;i<params.length;i++){
                String param = params[i];
                String value = values[i];

                String token = "token-"+i;
                outputStream.writeBytes("Content-Disposition: form-data; name=\""+param+"\"" + lineEnd);
                outputStream.writeBytes("Content-Type: text/plain;charset=UTF-8" + lineEnd);
                outputStream.writeBytes("Content-Length: " + token.length() + lineEnd);
                outputStream.writeBytes(lineEnd);
                outputStream.writeBytes(value + lineEnd);
                outputStream.writeBytes(twoHyphens + boundary + lineEnd);
            }//end or loop


            String connstr = "Content-Disposition: form-data; name=\"file\";filename=\""
                    + f.getAbsolutePath() + "\"" + lineEnd;

            outputStream.writeBytes(connstr);
            outputStream.writeBytes(lineEnd);

            bytesAvailable = fileInputStream.available();
            bufferSize = Math.min(bytesAvailable, maxBufferSize);
            buffer = new byte[bufferSize];

            // Read file
            bytesRead = fileInputStream.read(buffer, 0, bufferSize);
            try {
                while (bytesRead > 0) {
                    try {
                        outputStream.write(buffer, 0, bufferSize);

                    } catch (OutOfMemoryError e) {
                        e.printStackTrace();
                        Utils.logErrorMessage("outofmemoryerror");
                        response = "outofmemoryerror";
                    }
                    bytesAvailable = fileInputStream.available();
                    bufferSize = Math.min(bytesAvailable, maxBufferSize);
                    bytesRead = fileInputStream.read(buffer, 0, bufferSize);
                }
            } catch (Exception e) {
                e.printStackTrace();
                response = "error";
                Utils.logErrorMessage("exception: "+e.getMessage());
            }
            outputStream.writeBytes(lineEnd);
            outputStream.writeBytes(twoHyphens + boundary + twoHyphens
                    + lineEnd);

            // Responses from the server (code and message)
            int serverResponseCode = connection.getResponseCode();
            String serverResponseMessage = connection.getResponseMessage();


            if (serverResponseCode == 200) {
                response = "true";
            }
            else{

             if(retries!=0) {
                 uploadStuff(serverUrl, retries - 1, f, params, values);
             }
                  response = "false";
            }

            fileInputStream.close();
            outputStream.flush();

            //for android InputStream is = connection.getInputStream();
            java.io.InputStream is = connection.getInputStream();

            int ch;
            StringBuilder b = new StringBuilder();
            while( ( ch = is.read() ) != -1 ){
                b.append( (char)ch );
            }

            String responseString = b.toString();
            if(serverResponseCode == 200){
                onSuccess(responseString);
            }
            else{
                onError(responseString);
            }
            Utils.logErrorMessage("response string is " + responseString); //Here is the actual output

            outputStream.close();
            outputStream = null;

        } catch (Exception ex) {
            // Exception handling
            response = "error";

            ex.printStackTrace();
        }


       }
   }).start();
    }





    public abstract void onPreStart();
    public abstract void onSuccess(String response);

    public abstract void onError(String response);


}

我通常称之为:

        new HttpUploader() {
            @Override
            public void onPreStart() {}
            @Override
            public void onSuccess(final String response) {}
            @Override
            public void onError(final String response) {}
        }.uploadStuff(url, 5, imageSrc, new String[]{"key", "creator_name", "user_id", "user_phone"}, "file", Utils.owner.getFullName(), Utils.owner.getId(), Utils.owner.getFullPhoneNumber(),
                );

有什么方法可以纠正这个吗?

令我感到震惊的是,HttpUrlConnection暴露出代码找到服务器并且一切正常,但它根本没有将图像上传到服务器。

我在违规网络上使用了WhatsApp,并上传了任意大小的图片。我可以用什么黑客或解决方法来挽救局面? 感谢。

0 个答案:

没有答案