httpmultipartrequest.java

来自「Sony Ericsson手机上的Facebook客户端全套代码」· Java 代码 · 共 343 行

JAVA
343
字号
// Decompiled by Jad v1.5.7g. Copyright 2000 Pavel Kouznetsov.
// Jad home page: http://www.geocities.com/SiliconValley/Bridge/8617/jad.html
// Decompiler options: packimports(3) 
// Source File Name:   HttpMultipartRequest.java

package com.sonyericsson.fb.io;

import com.sonyericsson.fb.utils.Logger;
import java.io.*;
import java.util.Enumeration;
import java.util.Hashtable;
import javax.microedition.io.*;
import javax.microedition.io.file.FileConnection;

// Referenced classes of package com.sonyericsson.fb.io:
//            IFbProgressListener

public class HttpMultipartRequest
{

    public HttpMultipartRequest(HttpConnection connection)
    {
        _listener = null;
        _connection = null;
        _multipartPostData = "";
        _multipartBinaryData = new Hashtable();
        _multipartBinarySize = 0L;
        _bytesSent = 0L;
        _responseCode = 0;
        _responseLength = 0L;
        _responseMessage = "";
        _connection = connection;
    }

    public void SetListener(IFbProgressListener listener)
    {
        _listener = listener;
    }

    public boolean preparePostData(Hashtable postData)
    {
        return preparePostData(postData, true);
    }

    private boolean preparePostData(Hashtable postData, boolean includeCloseMultipart)
    {
        if(postData.size() == 0)
            return false;
        StringBuffer multipartBuffer = new StringBuffer("");
        for(Enumeration keys = postData.keys(); keys.hasMoreElements(); multipartBuffer.append("\r\n"))
        {
            String key = (String)keys.nextElement();
            String value = (String)postData.get(key);
            multipartBuffer.append("--SoMeTeXtWeWiLlNeVeRsEe\r\n");
            multipartBuffer.append("Content-Disposition: form-data; name=\"");
            multipartBuffer.append(key);
            multipartBuffer.append("\"\r\n\r\n");
            multipartBuffer.append(value);
        }

        if(includeCloseMultipart)
            multipartBuffer.append("--SoMeTeXtWeWiLlNeVeRsEe--\r\n");
        _multipartPostData = multipartBuffer.toString();
        return true;
    }

    public boolean prepareBinaryData(Hashtable postData, Hashtable binaryData)
    {
        Enumeration keys;
        if(postData.size() == 0 || binaryData.size() == 0)
            return false;
        boolean result = preparePostData(postData, false);
        if(!preparePostData(postData, false))
            return result;
        keys = binaryData.keys();
        _multipartBinarySize = 0L;
_L2:
        String filePath;
        String MIMEtype;
        if(!keys.hasMoreElements())
            break; /* Loop/switch isn't completed */
        filePath = (String)keys.nextElement();
        MIMEtype = (String)binaryData.get(filePath);
        FileConnection fc;
        long fileSize;
        fc = (FileConnection)Connector.open(filePath);
        fileSize = fc.fileSize();
        if(fileSize != -1L)
            break MISSING_BLOCK_LABEL_138;
        fc.close();
        Logger.printErrorln("HttpMultipartRequest.prepareBinaryData(): Could not read file size, probable cause is that file can't be found. Filename = " + filePath);
        return false;
        try
        {
            Logger.println("HttpMultipartRequest.prepareBinaryData(): file size = " + fileSize + "; file name = " + filePath);
            _multipartBinaryData.put(fc, MIMEtype);
            _multipartBinarySize += (long)("--SoMeTeXtWeWiLlNeVeRsEe\r\n".length() + "Content-Disposition: form-data; filename=\"".length() + fc.getName().length() + "\"\r\nContent-Type: ".length() + MIMEtype.length() + "\r\n\r\n".length()) + fileSize + (long)"\r\n".length();
        }
        catch(Exception e)
        {
            Logger.printErrorln("HttpMultipartRequest.prepareBinaryData(): Could not open file - " + e.toString());
            return false;
        }
        if(true) goto _L2; else goto _L1
_L1:
        _multipartBinarySize += "--SoMeTeXtWeWiLlNeVeRsEe--\r\n".length();
        return true;
    }

    public byte[] send()
    {
        long contentLength;
        InputStream is;
        ByteArrayOutputStream baos;
        OutputStream os;
        byte response[];
        if(_multipartPostData.length() == 0)
            return null;
        contentLength = (long)_multipartPostData.length() + _multipartBinarySize;
        if(_listener != null)
            _listener.progressStarted(contentLength);
        is = null;
        baos = new ByteArrayOutputStream();
        os = null;
        response = null;
        _connection.setRequestProperty("Connection", "close");
        _connection.setRequestProperty("Content-Type", "multipart/form-data; boundary=SoMeTeXtWeWiLlNeVeRsEe");
        _connection.setRequestProperty("Content-Length", String.valueOf(contentLength));
        if(_multipartBinarySize > 0L)
            _connection.setRequestProperty("MIME-version", "1.0");
        _connection.setRequestMethod("POST");
        Logger.println("Going to post multipart data to server: " + _connection.getURL() + "; length = " + String.valueOf(contentLength));
        os = _connection.openOutputStream();
        os.write(_multipartPostData.getBytes());
        _bytesSent = _multipartPostData.getBytes().length;
        if(_listener != null)
            _listener.progress(_multipartPostData.length());
        if(_multipartBinarySize > 0L)
        {
            Logger.println("Going to post multipart binary data to server; length = " + _multipartBinarySize);
            writeBinaryData(os);
        }
        if(_bytesSent != contentLength)
            Logger.printErrorln("Data mismatch! Did not send as much as supposed to. " + _bytesSent + " != " + contentLength);
        is = requestResponseStream();
        break MISSING_BLOCK_LABEL_420;
        IOException e;
        e;
        byte abyte0[];
        Logger.printErrorln("HttpMultipartRequest.send(): Request could not be completed, response code = " + _responseCode);
        abyte0 = response;
        try
        {
            if(os != null)
                os.close();
            if(baos != null)
                baos.close();
            if(is != null)
                is.close();
        }
        catch(Exception closeException)
        {
            Logger.printErrorln("HttpMultipartRequest.send(): Could not close stream: " + closeException.toString());
        }
        return abyte0;
        Logger.println("HttpMultipartRequest.send(): Server responded with response code: " + _responseCode);
        if(_responseLength != -1L)
            response = getBytes(is, (int)_responseLength);
        else
            response = getBytes(is);
        try
        {
            if(os != null)
                os.close();
            if(baos != null)
                baos.close();
            if(is != null)
                is.close();
        }
        catch(Exception closeException)
        {
            Logger.printErrorln("HttpMultipartRequest.send(): Could not close stream: " + closeException.toString());
        }
        break MISSING_BLOCK_LABEL_714;
        IOException exception;
        exception;
        if(_listener != null)
            _listener.progressError();
        Logger.printErrorln("HttpMultipartRequest.send(): Could not post the multipart message: " + exception.toString());
        abyte0 = response;
        try
        {
            if(os != null)
                os.close();
            if(baos != null)
                baos.close();
            if(is != null)
                is.close();
        }
        catch(Exception closeException)
        {
            Logger.printErrorln("HttpMultipartRequest.send(): Could not close stream: " + closeException.toString());
        }
        return abyte0;
        Exception exception1;
        exception1;
        try
        {
            if(os != null)
                os.close();
            if(baos != null)
                baos.close();
            if(is != null)
                is.close();
        }
        catch(Exception closeException)
        {
            Logger.printErrorln("HttpMultipartRequest.send(): Could not close stream: " + closeException.toString());
        }
        throw exception1;
        if(_listener != null)
            _listener.progressFinished();
        Logger.println("HttpMultipartRequest.send(): Server responded with message: " + new String(response));
        return response;
    }

    private InputStream requestResponseStream()
        throws IOException
    {
        _responseLength = _connection.getLength();
        _responseCode = _connection.getResponseCode();
        _responseMessage = _connection.getResponseMessage();
        if(_responseCode != 200)
            throw new IOException("HTTP connection to URL: '" + _connection.getURL() + "' returned response: " + _responseCode + " " + _responseMessage);
        else
            return _connection.openInputStream();
    }

    private byte[] getBytes(InputStream in, int length)
        throws IOException
    {
        int offset = 0;
        byte data[] = new byte[length];
        for(; offset < length; offset += in.read(data, offset, length - offset));
        return data;
    }

    private byte[] getBytes(InputStream in)
        throws IOException
    {
        byte buffer[] = new byte[2048];
        ByteArrayOutputStream bytes = new ByteArrayOutputStream();
        do
        {
            int bytesRead = in.read(buffer);
            if(bytesRead != -1)
            {
                bytes.write(buffer, 0, bytesRead);
            } else
            {
                bytes.flush();
                byte data[] = bytes.toByteArray();
                bytes.close();
                _responseLength = data.length;
                return data;
            }
        } while(true);
    }

    private void writeBinaryData(OutputStream os)
        throws IOException
    {
        byte buffer[] = new byte[0x10000];
        for(Enumeration e = _multipartBinaryData.keys(); e.hasMoreElements();)
        {
            FileConnection fc = (FileConnection)e.nextElement();
            InputStream is = fc.openInputStream();
            String MIMEtype = (String)_multipartBinaryData.get(fc);
            StringBuffer headerBuffer = new StringBuffer("");
            headerBuffer.append("--SoMeTeXtWeWiLlNeVeRsEe\r\n");
            headerBuffer.append("Content-Disposition: form-data; filename=\"");
            headerBuffer.append(fc.getName());
            headerBuffer.append("\"\r\nContent-Type: ");
            headerBuffer.append(MIMEtype);
            headerBuffer.append("\r\n\r\n");
            Logger.println("Writing content-disposition header for file: " + fc.getName());
            os.write(headerBuffer.toString().getBytes());
            _bytesSent += headerBuffer.toString().getBytes().length;
            if(_listener != null)
                _listener.progress(headerBuffer.length());
            long bytesToWrite = fc.fileSize();
            int totalBytesRead = 0;
            do
            {
                if(bytesToWrite <= 0L)
                    break;
                int bytesToRead = (int)Math.min(0x10000L, bytesToWrite);
                int bytesRead = is.read(buffer, 0, bytesToRead);
                Logger.println(bytesRead + " bytes read from file.");
                if(bytesRead < 0)
                    throw new IOException("HttpMultipartRequest.writeBinaryData(): read requested(" + bytesToRead + ") != actually read(" + bytesRead + ").");
                if(bytesRead > 0)
                {
                    totalBytesRead += bytesRead;
                    os.write(buffer, 0, bytesRead);
                    bytesToWrite -= bytesRead;
                    _bytesSent += bytesRead;
                    if(_listener != null)
                        _listener.progress(bytesRead);
                }
            } while(true);
            Logger.println("Writing multipart package end.");
            os.write("\r\n".getBytes());
            _bytesSent += "\r\n".getBytes().length;
        }

        Logger.println("Writing multipart boundry end.");
        os.write("--SoMeTeXtWeWiLlNeVeRsEe--\r\n".getBytes());
        _bytesSent += "--SoMeTeXtWeWiLlNeVeRsEe--\r\n".getBytes().length;
    }

    static final String BOUNDARY = "----------V2ymHFg03ehbqgZCaKO6jy";
    private static final String CONTENT_TYPE_HEADER = "multipart/form-data; boundary=SoMeTeXtWeWiLlNeVeRsEe";
    private static final String MULTIPART_BOUNDRY = "--SoMeTeXtWeWiLlNeVeRsEe\r\n";
    private static final String MULTIPART_BOUNDRY_END = "--SoMeTeXtWeWiLlNeVeRsEe--\r\n";
    private static final String CONTENT_DISPOSITION_HEADER_PART1 = "Content-Disposition: form-data; name=\"";
    private static final String CONTENT_DISPOSITION_HEADER_PART2 = "\"\r\n\r\n";
    private static final String CONTENT_DISPOSITION_HEADER_BINARY_PART1 = "Content-Disposition: form-data; filename=\"";
    private static final String CONTENT_DISPOSITION_HEADER_BINARY_PART2 = "\"\r\nContent-Type: ";
    private static final String CONTENT_DISPOSITION_HEADER_BINARY_PART3 = "\r\n\r\n";
    private static final int BINARY_MULTIPART_CHUNK_SIZE = 0x10000;
    private static final int BUFFER_SIZE = 2048;
    private IFbProgressListener _listener;
    private HttpConnection _connection;
    private String _multipartPostData;
    private Hashtable _multipartBinaryData;
    private long _multipartBinarySize;
    private long _bytesSent;
    private int _responseCode;
    private long _responseLength;
    private String _responseMessage;
}

⌨️ 快捷键说明

复制代码Ctrl + C
搜索代码Ctrl + F
全屏模式F11
增大字号Ctrl + =
减小字号Ctrl + -
显示快捷键?