在android中的multipart上的服务器上传文件

时间:2014-09-12 07:21:08

标签: android proxy android-networking androidhttpclient

我在服务器上以multipart上传文件,如果设备上没有代理设置但在代理上它不起作用,它可以正常工作。见下面的代码 -

public int uploadFile(String sourceFileUri, String upLoadServerUri) {
    int serverResponseCode = 0;

    String fileName = sourceFileUri;

    HttpURLConnection conn = null;
    DataOutputStream dos = null;
    String lineEnd = "\r\n";
    String twoHyphens = "--";
    String boundary = "*****";
    int bytesRead, bytesAvailable, bufferSize;
    byte[] buffer;
    int maxBufferSize = 1 * 1024 * 1024;
    File sourceFile = new File(sourceFileUri);

    if (!sourceFile.isFile()) {
    } else {
        try {

            // open a URL connection to the Servlet
            FileInputStream fileInputStream = new FileInputStream(
                    sourceFile);
            URL url = new URL(upLoadServerUri);

            boolean isProxy = true;
            ConnectivityManager cm = (ConnectivityManager) AppService
                    .getAppService().getApplicationContext()
                    .getSystemService(Context.CONNECTIVITY_SERVICE);
            if (cm != null) {
                NetworkInfo ni = cm.getActiveNetworkInfo();
                if (ni != null) {
                    if (!ni.getTypeName().equals("WIFI")) {
                        isProxy = false;
                    }
                    if (isProxy) {
                        Proxy proxy = new Proxy(java.net.Proxy.Type.HTTP,
                                new InetSocketAddress(
                                        android.net.Proxy.getDefaultHost(),
                                        android.net.Proxy.getDefaultPort()));
                        conn = (HttpURLConnection) url
                                .openConnection(proxy);

                    } else {
                        conn = (HttpURLConnection) url.openConnection();
                    }
                }
            }

            // Open a HTTP connection to the URL
            // 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(
                    "Authorization",
                    "Bearer "
                            + CommonFunctions.getAccessToken(AppService
                                    .getAppService()
                                    .getApplicationContext()));
            conn.setRequestProperty("uploaded_file", fileName);

            dos = new DataOutputStream(conn.getOutputStream());

            dos.writeBytes(lineEnd + twoHyphens + boundary + lineEnd);
            dos.writeBytes("Content-Disposition: form-data; name=\"userfile\"; filename=\"filename.xml\"\r\n");
            dos.writeBytes("Content-Type: text/xml" + lineEnd + 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);

            if (serverResponseCode == 200 || serverResponseCode == 204) {
                offlineAnalyticsOperations();
            } else {
                // for now unless code is restructured
                if (NetUtils.isNetworkConnected(AppService.getAppService()
                        .getApplicationContext())) {
                    offlineAnalyticsOperations();
                }

            }

            // close the streams //
            fileInputStream.close();
            dos.flush();
            dos.close();

        } catch (MalformedURLException ex) {
            Log.v("msg", ex.getMessage());

        } catch (Exception e) {
            Log.v("msg", e.getMessage());

        }


    } // End else block
    return serverResponseCode;
}

我也不知道代理,端口和密码。我不能向用户询问此信息。我怎样才能做到这一点?以及它为什么不在代理上工作。我正在使用其他API获取json响应那些没有给我这样的错误(我通过httpConnection得到的)和在这个文件上传我使用url连接。那是问题吗?我已尝试使用httpConnection,但它不能同时代理和非代理。 我的网络很差。所以不理解这个问题。 提前谢谢。

0 个答案:

没有答案