Example usage for org.apache.commons.httpclient.methods.multipart ByteArrayPartSource ByteArrayPartSource

List of usage examples for org.apache.commons.httpclient.methods.multipart ByteArrayPartSource ByteArrayPartSource

Introduction

In this page you can find the example usage for org.apache.commons.httpclient.methods.multipart ByteArrayPartSource ByteArrayPartSource.

Prototype

public ByteArrayPartSource(String paramString, byte[] paramArrayOfByte) 

Source Link

Usage

From source file:hk.hku.cecid.corvus.http.PartnershipSender.java

/** 
 * [@EVENT] This method is invoked when the sender is required to create a HTTP Request from configuration.
 * <br/><br/>//from  w w  w . j  a  va  2s . com
 * It generates a multi-part content embedded in the HTTP POST request. The multi-part content
 * contains all partnership data with the parameter name retrieved from the partnership mapping.
 * {@link #getPartnershipMapping()}. Also the type of partnership operation is appended 
 * at the end of multi-part with parameter name equal to 'request_action' and it's value 
 * is extracted thru {@link #getPartnershipOperationMapping()}.
 */
protected HttpMethod onCreateRequest() throws Exception {
    // Validate main parameter.
    Map data = ((KVPairData) this.properties).getProperties();
    Map data2webFormName = this.getPartnershipMapping();

    if (data2webFormName == null)
        throw new NullPointerException("Missing partnership mapping for creating HTTP request");

    // Create the HTTP POST method targeted to service end-point.
    PostMethod post = new PostMethod(this.getServiceEndPoint().toExternalForm());
    List parts = new ArrayList(); // An array for multi-part;       

    /* 
     * For each data key in the partnership data, create a String multi-part
     * with the request parameter name equal to the mapping from the data key.  
     * 
     * For the field like verification / encryption certificates, it creates
     * a byte array multi-part source. 
     */
    Iterator itr = data2webFormName.entrySet().iterator();
    Map.Entry e; // an entry representing the partnership data to web form name mapping.
    String formParamName; // a temporary pointer pointing to the value in the entry.
    Object dataValue; // a temporary pointer pointing to the value in the partnership data.
    Part newPart; // a temporary pointer pointing to a multi-part part.

    while (itr.hasNext()) {
        e = (Map.Entry) itr.next();
        formParamName = (String) e.getValue();
        // Add new part if the mapped key is not null.
        if (e.getValue() != null) {
            dataValue = data.get(e.getKey());
            if (dataValue == null) // Use empty string when the key is not filled.
                dataValue = "";
            if (dataValue instanceof String) { // Create literal part               
                newPart = new StringPart(formParamName, (String) dataValue);
            } else if (dataValue instanceof byte[]) { // Create streaming multi-part
                PartSource source = new ByteArrayPartSource((String) e.getKey(), (byte[]) dataValue);
                newPart = new FilePart(formParamName, source);
            } else if (dataValue instanceof Boolean) {
                newPart = new StringPart(formParamName, String.valueOf((Boolean) dataValue));
            } else {
                newPart = new StringPart(formParamName, dataValue.toString());
            }
            // Add the new part.
            parts.add(newPart);
        }
    }

    Map partnershipOpMap = this.getPartnershipOperationMapping();
    /* Add HTTP request action to the web form parameter. */
    parts.add(new StringPart("request_action", (String) partnershipOpMap.get(new Integer(this.pOp))));

    MultipartRequestEntity multipartRequest = new MultipartRequestEntity((Part[]) parts.toArray(new Part[] {}),
            post.getParams());

    post.setRequestEntity(multipartRequest);
    return post;
}

From source file:edu.umd.cs.submit.CommandLineSubmit.java

/**
 * @param p/* ww w . j a  v  a2 s .  co m*/
 * @param find
 * @param files
 * @param userProps
 * @return
 * @throws IOException
 * @throws FileNotFoundException
 */
public static MultipartPostMethod createFilePost(Properties p, FindAllFiles find, Collection<File> files,
        Properties userProps) throws IOException, FileNotFoundException {
    // ========================== assemble zip file in byte array
    // ==============================
    String loginName = userProps.getProperty("loginName");
    String classAccount = userProps.getProperty("classAccount");
    String from = classAccount;
    if (loginName != null && !loginName.equals(classAccount))
        from += "/" + loginName;
    System.out.println(" submitted by " + from);
    System.out.println();
    System.out.println("Submitting the following files");
    ByteArrayOutputStream bytes = new ByteArrayOutputStream(4096);
    byte[] buf = new byte[4096];
    ZipOutputStream zipfile = new ZipOutputStream(bytes);
    zipfile.setComment("zipfile for CommandLineTurnin, version " + VERSION);
    for (File resource : files) {
        if (resource.isDirectory())
            continue;
        String relativePath = resource.getCanonicalPath().substring(find.rootPathLength + 1);
        System.out.println(relativePath);
        ZipEntry entry = new ZipEntry(relativePath);
        entry.setTime(resource.lastModified());

        zipfile.putNextEntry(entry);
        InputStream in = new FileInputStream(resource);
        try {
            while (true) {
                int n = in.read(buf);
                if (n < 0)
                    break;
                zipfile.write(buf, 0, n);
            }
        } finally {
            in.close();
        }
        zipfile.closeEntry();

    } // for each file
    zipfile.close();

    MultipartPostMethod filePost = new MultipartPostMethod(p.getProperty("submitURL"));

    p.putAll(userProps);
    // add properties
    for (Map.Entry<?, ?> e : p.entrySet()) {
        String key = (String) e.getKey();
        String value = (String) e.getValue();
        if (!key.equals("submitURL"))
            filePost.addParameter(key, value);
    }
    filePost.addParameter("submitClientTool", "CommandLineTool");
    filePost.addParameter("submitClientVersion", VERSION);
    byte[] allInput = bytes.toByteArray();
    filePost.addPart(new FilePart("submittedFiles", new ByteArrayPartSource("submit.zip", allInput)));
    return filePost;
}

From source file:com.groupon.odo.HttpUtilities.java

/**
 * Sets up the given {@link org.apache.commons.httpclient.methods.PostMethod} to send the same multipart POST data
 * as was sent in the given {@link HttpServletRequest}
 *
 * @param postMethodProxyRequest The {@link org.apache.commons.httpclient.methods.PostMethod} that we are configuring to send a
 *                               multipart POST request
 * @param httpServletRequest     The {@link HttpServletRequest} that contains the multipart
 *                               POST data to be sent via the {@link org.apache.commons.httpclient.methods.PostMethod}
 *///w ww.  ja  v  a  2s .  com
@SuppressWarnings("unchecked")
public static void handleMultipartPost(EntityEnclosingMethod postMethodProxyRequest,
        HttpServletRequest httpServletRequest, DiskFileItemFactory diskFileItemFactory)
        throws ServletException {

    // Create a new file upload handler
    ServletFileUpload servletFileUpload = new ServletFileUpload(diskFileItemFactory);
    // Parse the request
    try {
        // Get the multipart items as a list
        List<FileItem> listFileItems = (List<FileItem>) servletFileUpload.parseRequest(httpServletRequest);
        // Create a list to hold all of the parts
        List<Part> listParts = new ArrayList<Part>();
        // Iterate the multipart items list
        for (FileItem fileItemCurrent : listFileItems) {
            // If the current item is a form field, then create a string
            // part
            if (fileItemCurrent.isFormField()) {
                StringPart stringPart = new StringPart(fileItemCurrent.getFieldName(), // The field name
                        fileItemCurrent.getString() // The field value
                );
                // Add the part to the list
                listParts.add(stringPart);
            } else {
                // The item is a file upload, so we create a FilePart
                FilePart filePart = new FilePart(fileItemCurrent.getFieldName(), // The field name
                        new ByteArrayPartSource(fileItemCurrent.getName(), // The uploaded file name
                                fileItemCurrent.get() // The uploaded file contents
                        ));
                // Add the part to the list
                listParts.add(filePart);
            }
        }
        MultipartRequestEntity multipartRequestEntity = new MultipartRequestEntity(
                listParts.toArray(new Part[listParts.size()]), postMethodProxyRequest.getParams());

        postMethodProxyRequest.setRequestEntity(multipartRequestEntity);

        // The current content-type header (received from the client) IS of
        // type "multipart/form-data", but the content-type header also
        // contains the chunk boundary string of the chunks. Currently, this
        // header is using the boundary of the client request, since we
        // blindly copied all headers from the client request to the proxy
        // request. However, we are creating a new request with a new chunk
        // boundary string, so it is necessary that we re-set the
        // content-type string to reflect the new chunk boundary string
        postMethodProxyRequest.setRequestHeader(STRING_CONTENT_TYPE_HEADER_NAME,
                multipartRequestEntity.getContentType());
    } catch (FileUploadException fileUploadException) {
        throw new ServletException(fileUploadException);
    }
}

From source file:edu.umd.cs.eclipse.courseProjectManager.EclipseLaunchEventLog.java

/**
 * Uploads a String containing eclipse launch events to the server.
 * //from w w  w.  j a v  a 2  s .co  m
 * @param launchEvents
 *            the eclipse launch events to be uploaded
 * @param classAccount
 *            the class account of the user who generated the launch events
 * @param oneTimePassword
 *            the one-time password of the user who generated the launch
 *            events
 * @param url
 *            the URL of the server that will accept the launch events
 * @throws IOException
 * @throws HttpException
 */
private static int uploadMessages(String launchEvents, Properties props) throws IOException, HttpException {
    // Replace the path with /eclipse/LogEclipseLaunchEvent.
    if (!props.containsKey("submitURL")) {
        props.put("submitURL", "https://submit.cs.umd.edu:8443/eclipse/LogEclipseLaunchEvent");
    }
    String submitURL = props.getProperty("submitURL");
    Debug.print("submitURL: " + props.getProperty("submitURL"));
    int index = submitURL.indexOf("/eclipse/");
    if (index == -1) {
        Debug.print("Cannot find submitURL in .submitUser file");
        throw new IOException("Cannot find submitURL in .submitUser file");
    }
    submitURL = submitURL.substring(0, index) + "/eclipse/LogEclipseLaunchEvent";
    String version = System.getProperties().getProperty("java.runtime.version");
    boolean useEasyHttps = version.startsWith("1.3") || version.startsWith("1.2") || version.startsWith("1.4.0")
            || version.startsWith("1.4.1") || version.startsWith("1.4.2_0") && version.charAt(7) < '5';
    if (useEasyHttps) {
        if (submitURL.startsWith("https"))
            submitURL = "easy" + submitURL;
    }
    Debug.print("submitURL: " + submitURL);
    MultipartPostMethod filePost = new MultipartPostMethod(submitURL);

    // add filepart
    byte[] bytes = launchEvents.getBytes();
    filePost.addPart(new FilePart("eclipseLaunchEvent", new ByteArrayPartSource("eclipseLaunchEvent", bytes)));

    TurninProjectAction.addAllPropertiesButSubmitURL(props, filePost);

    filePost.addParameter("clientTime", Long.toString(System.currentTimeMillis()));

    HttpClient client = new HttpClient();
    client.setConnectionTimeout(5000);

    int status = client.executeMethod(filePost);
    if (status != HttpStatus.SC_OK) {
        System.err.println(filePost.getResponseBodyAsString());
        throw new HttpException("status is: " + status);
    }
    return status;
}

From source file:com.zimbra.qa.unittest.TestFileUpload.java

@Test
public void testAdminUploadWithCsrfInFormField() throws Exception {
    SoapHttpTransport transport = new SoapHttpTransport(TestUtil.getAdminSoapUrl());
    com.zimbra.soap.admin.message.AuthRequest req = new com.zimbra.soap.admin.message.AuthRequest(
            LC.zimbra_ldap_user.value(), LC.zimbra_ldap_password.value());
    req.setCsrfSupported(true);/*from  w w  w.ja  va 2s  . c om*/
    Element response = transport.invoke(JaxbUtil.jaxbToElement(req, SoapProtocol.SoapJS.getFactory()));
    com.zimbra.soap.admin.message.AuthResponse authResp = JaxbUtil.elementToJaxb(response);
    String authToken = authResp.getAuthToken();
    String csrfToken = authResp.getCsrfToken();
    int port = 7071;
    try {
        port = Provisioning.getInstance().getLocalServer().getIntAttr(Provisioning.A_zimbraAdminPort, 0);
    } catch (ServiceException e) {
        ZimbraLog.test.error("Unable to get admin SOAP port", e);
    }
    String Url = "https://localhost:" + port + ADMIN_UPLOAD_URL;
    PostMethod post = new PostMethod(Url);
    FilePart part = new FilePart(FILE_NAME, new ByteArrayPartSource(FILE_NAME, "some file content".getBytes()));
    Part csrfPart = new StringPart("csrfToken", csrfToken);
    String contentType = "application/x-msdownload";
    part.setContentType(contentType);
    HttpClient client = ZimbraHttpConnectionManager.getInternalHttpConnMgr().newHttpClient();
    HttpState state = new HttpState();
    state.addCookie(new org.apache.commons.httpclient.Cookie("localhost",
            ZimbraCookie.authTokenCookieName(true), authToken, "/", null, false));
    client.getParams().setCookiePolicy(CookiePolicy.BROWSER_COMPATIBILITY);
    client.setState(state);
    post.setRequestEntity(new MultipartRequestEntity(new Part[] { part, csrfPart }, post.getParams()));
    int statusCode = HttpClientUtil.executeMethod(client, post);
    assertEquals("This request should succeed. Getting status code " + statusCode, HttpStatus.SC_OK,
            statusCode);
    String resp = post.getResponseBodyAsString();
    assertNotNull("Response should not be empty", resp);
    assertTrue("Incorrect HTML response", resp.contains(RESP_STR));
}

From source file:fr.paris.lutece.portal.web.upload.UploadServletTest.java

private MockHttpServletRequest getMultipartRequest() throws Exception {
    MockHttpServletRequest request = new MockHttpServletRequest();
    byte[] fileContent = new byte[] { 1, 2, 3 };
    Part[] parts = new Part[] { new FilePart("file1", new ByteArrayPartSource("file1", fileContent)) };
    MultipartRequestEntity multipartRequestEntity = new MultipartRequestEntity(parts,
            new PostMethod().getParams());
    // Serialize request body
    ByteArrayOutputStream requestContent = new ByteArrayOutputStream();
    multipartRequestEntity.writeRequest(requestContent);
    // Set request body to HTTP servlet request
    request.setContent(requestContent.toByteArray());
    // Set content type to HTTP servlet request (important, includes Mime boundary string)
    request.setContentType(multipartRequestEntity.getContentType());
    request.setMethod("POST");
    return request;
}

From source file:com.sourcesense.confluence.servlets.CMISProxyServlet.java

/**
 * Sets up the given {@link PostMethod} to send the same multipart POST
 * data as was sent in the given {@link HttpServletRequest}
 *
 * @param postMethodProxyRequest The {@link PostMethod} that we are
 *                               configuring to send a multipart POST request
 * @param httpServletRequest     The {@link HttpServletRequest} that contains
 *                               the mutlipart POST data to be sent via the {@link PostMethod}
 * @throws javax.servlet.ServletException If something fails when uploading the content to the server
 *//*from w  ww.  j a va 2s .c  o m*/
@SuppressWarnings({ "unchecked", "ToArrayCallWithZeroLengthArrayArgument" })
private void handleMultipartPost(PostMethod postMethodProxyRequest, HttpServletRequest httpServletRequest)
        throws ServletException {
    // Create a factory for disk-based file items
    DiskFileItemFactory diskFileItemFactory = new DiskFileItemFactory();
    // Set factory constraints
    diskFileItemFactory.setSizeThreshold(this.getMaxFileUploadSize());
    diskFileItemFactory.setRepository(FILE_UPLOAD_TEMP_DIRECTORY);
    // Create a new file upload handler
    ServletFileUpload servletFileUpload = new ServletFileUpload(diskFileItemFactory);
    // Parse the request
    try {
        // Get the multipart items as a list
        List<FileItem> listFileItems = (List<FileItem>) servletFileUpload.parseRequest(httpServletRequest);
        // Create a list to hold all of the parts
        List<Part> listParts = new ArrayList<Part>();
        // Iterate the multipart items list
        for (FileItem fileItemCurrent : listFileItems) {
            // If the current item is a form field, then create a string part
            if (fileItemCurrent.isFormField()) {
                StringPart stringPart = new StringPart(fileItemCurrent.getFieldName(), // The field name
                        fileItemCurrent.getString() // The field value
                );
                // Add the part to the list
                listParts.add(stringPart);
            } else {
                // The item is a file upload, so we create a FilePart
                FilePart filePart = new FilePart(fileItemCurrent.getFieldName(), // The field name
                        new ByteArrayPartSource(fileItemCurrent.getName(), // The uploaded file name
                                fileItemCurrent.get() // The uploaded file contents
                        ));
                // Add the part to the list
                listParts.add(filePart);
            }
        }
        MultipartRequestEntity multipartRequestEntity = new MultipartRequestEntity(
                listParts.toArray(new Part[] {}), postMethodProxyRequest.getParams());
        postMethodProxyRequest.setRequestEntity(multipartRequestEntity);
        // The current content-type header (received from the client) IS of
        // type "multipart/form-data", but the content-type header also
        // contains the chunk boundary string of the chunks. Currently, this
        // header is using the boundary of the client request, since we
        // blindly copied all headers from the client request to the proxy
        // request. However, we are creating a new request with a new chunk
        // boundary string, so it is necessary that we re-set the
        // content-type string to reflect the new chunk boundary string
        postMethodProxyRequest.setRequestHeader(STRING_CONTENT_TYPE_HEADER_NAME,
                multipartRequestEntity.getContentType());
    } catch (FileUploadException fileUploadException) {
        throw new ServletException(fileUploadException);
    }
}

From source file:com.wordpress.metaphorm.authProxy.httpClient.impl.OAuthProxyConnectionApacheHttpCommonsClientImpl.java

/**
 * Sets up the given {@link PostMethod} to send the same multipart POST
 * data as was sent in the given {@link HttpServletRequest}
 * @param postMethodProxyRequest The {@link PostMethod} that we are
 *                                configuring to send a multipart POST request
 * @param httpServletRequest The {@link HttpServletRequest} that contains
 *                            the mutlipart POST data to be sent via the {@link PostMethod}
 *//*  www  .ja v  a 2s  . c  o m*/
@SuppressWarnings("unchecked")
private void handleMultipartPost(PostMethod postMethodProxyRequest, HttpServletRequest httpServletRequest)
        throws IOException {

    _log.debug("handleMultipartPost()");

    // Create a factory for disk-based file items
    DiskFileItemFactory diskFileItemFactory = new DiskFileItemFactory();
    // Set factory constraints
    diskFileItemFactory.setSizeThreshold(this.getMaxFileUploadSize());
    diskFileItemFactory.setRepository(FILE_UPLOAD_TEMP_DIRECTORY);
    // Create a new file upload handler
    ServletFileUpload servletFileUpload = new ServletFileUpload(diskFileItemFactory);
    // Parse the request
    try {
        // Get the multipart items as a list
        List<FileItem> listFileItems = (List<FileItem>) servletFileUpload.parseRequest(httpServletRequest);
        // Create a list to hold all of the parts
        List<Part> listParts = new ArrayList<Part>();
        // Iterate the multipart items list
        for (FileItem fileItemCurrent : listFileItems) {
            // If the current item is a form field, then create a string part
            if (fileItemCurrent.isFormField()) {
                StringPart stringPart = new StringPart(fileItemCurrent.getFieldName(), // The field name
                        fileItemCurrent.getString() // The field value
                );
                // Add the part to the list
                listParts.add(stringPart);
            } else {
                // The item is a file upload, so we create a FilePart
                FilePart filePart = new FilePart(fileItemCurrent.getFieldName(), // The field name
                        new ByteArrayPartSource(fileItemCurrent.getName(), // The uploaded file name
                                fileItemCurrent.get() // The uploaded file contents
                        ));
                // Add the part to the list
                listParts.add(filePart);
            }
        }
        MultipartRequestEntity multipartRequestEntity = new MultipartRequestEntity(
                listParts.toArray(new Part[] {}), postMethodProxyRequest.getParams());
        postMethodProxyRequest.setRequestEntity(multipartRequestEntity);
        // The current content-type header (received from the client) IS of
        // type "multipart/form-data", but the content-type header also
        // contains the chunk boundary string of the chunks. Currently, this
        // header is using the boundary of the client request, since we
        // blindly copied all headers from the client request to the proxy
        // request. However, we are creating a new request with a new chunk
        // boundary string, so it is necessary that we re-set the
        // content-type string to reflect the new chunk boundary string
        postMethodProxyRequest.setRequestHeader(HttpConstants.STRING_CONTENT_TYPE_HEADER_NAME,
                multipartRequestEntity.getContentType());
    } catch (FileUploadException fileUploadException) {
        throw new IOException(fileUploadException);
    }
}

From source file:com.qlkh.client.server.proxy.ProxyServlet.java

/**
 * Sets up the given {@link org.apache.commons.httpclient.methods.PostMethod} to send the same multipart POST
 * data as was sent in the given {@link javax.servlet.http.HttpServletRequest}
 *
 * @param postMethodProxyRequest The {@link org.apache.commons.httpclient.methods.PostMethod} that we are
 *                               configuring to send a multipart POST request
 * @param httpServletRequest     The {@link javax.servlet.http.HttpServletRequest} that contains
 *                               the mutlipart POST data to be sent via the {@link org.apache.commons.httpclient.methods.PostMethod}
 *///from  w w w .j a v  a2  s.c  o  m
@SuppressWarnings("unchecked")
private void handleMultipartPost(PostMethod postMethodProxyRequest, HttpServletRequest httpServletRequest)
        throws ServletException {
    // Create a factory for disk-based file items
    DiskFileItemFactory diskFileItemFactory = new DiskFileItemFactory();
    // Set factory constraints
    diskFileItemFactory.setSizeThreshold(this.getMaxFileUploadSize());
    diskFileItemFactory.setRepository(FILE_UPLOAD_TEMP_DIRECTORY);
    // Create a new file upload handler
    ServletFileUpload servletFileUpload = new ServletFileUpload(diskFileItemFactory);
    // Parse the request
    try {
        // Get the multipart items as a list
        List<FileItem> listFileItems = (List<FileItem>) servletFileUpload.parseRequest(httpServletRequest);
        // Create a list to hold all of the parts
        List<Part> listParts = new ArrayList<Part>();
        // Iterate the multipart items list
        for (FileItem fileItemCurrent : listFileItems) {
            // If the current item is a form field, then create a string part
            if (fileItemCurrent.isFormField()) {
                StringPart stringPart = new StringPart(fileItemCurrent.getFieldName(), // The field name
                        fileItemCurrent.getString() // The field value
                );
                // Add the part to the list
                listParts.add(stringPart);
            } else {
                // The item is a file upload, so we create a FilePart
                FilePart filePart = new FilePart(fileItemCurrent.getFieldName(), // The field name
                        new ByteArrayPartSource(fileItemCurrent.getName(), // The uploaded file name
                                fileItemCurrent.get() // The uploaded file contents
                        ));
                // Add the part to the list
                listParts.add(filePart);
            }
        }
        MultipartRequestEntity multipartRequestEntity = new MultipartRequestEntity(
                listParts.toArray(new Part[] {}), postMethodProxyRequest.getParams());
        postMethodProxyRequest.setRequestEntity(multipartRequestEntity);
        // The current content-type header (received from the client) IS of
        // type "multipart/form-data", but the content-type header also
        // contains the chunk boundary string of the chunks. Currently, this
        // header is using the boundary of the client request, since we
        // blindly copied all headers from the client request to the proxy
        // request. However, we are creating a new request with a new chunk
        // boundary string, so it is necessary that we re-set the
        // content-type string to reflect the new chunk boundary string
        postMethodProxyRequest.setRequestHeader(STRING_CONTENT_TYPE_HEADER_NAME,
                multipartRequestEntity.getContentType());
    } catch (FileUploadException fileUploadException) {
        throw new ServletException(fileUploadException);
    }
}

From source file:net.exclaimindustries.geohashdroid.wiki.WikiUtils.java

/** Uploads an image to the wiki
   @param  httpclient  an active HTTP session, wiki login has to have happened before.
   @param  filename    the name of the new image file
   @param  description the description of the image. An initial description will be used as page content for the image's wiki page
   @param  formfields  a formfields hash as modified by getWikiPage containing an edittoken we can use (see the MediaWiki API for reasons why)
   @param  data        a ByteArray containing the raw image data (assuming jpeg encoding, currently).
*/// ww w .j a va  2 s . c  o m
public static void putWikiImage(HttpClient httpclient, String filename, String description,
        HashMap<String, String> formfields, byte[] data) throws Exception {
    if (!formfields.containsKey("token")) {
        throw new WikiException(R.string.wiki_error_unknown);
    }

    HttpPost httppost = new HttpPost(WIKI_API_URL);

    // First, we need an edit token.  Let's get one.
    ArrayList<NameValuePair> tnvps = new ArrayList<NameValuePair>();
    tnvps.add(new BasicNameValuePair("action", "query"));
    tnvps.add(new BasicNameValuePair("prop", "info"));
    tnvps.add(new BasicNameValuePair("intoken", "edit"));
    tnvps.add(new BasicNameValuePair("titles", "UPLOAD_AN_IMAGE"));
    tnvps.add(new BasicNameValuePair("format", "xml"));

    httppost.setEntity(new UrlEncodedFormEntity(tnvps, "utf-8"));
    Document response = getHttpDocument(httpclient, httppost);

    Element root = response.getDocumentElement();

    // Hopefully, a token exists.  If not, a problem exists.
    String token;
    Element page;
    try {
        page = DOMUtil.getFirstElement(root, "page");
        token = DOMUtil.getSimpleAttributeText(page, "edittoken");
    } catch (Exception e) {
        throw new WikiException(R.string.wiki_error_xml);
    }

    // TOKEN GET!  Now we've got us enough to get our upload on!
    Part[] nvps = new Part[] { new StringPart("action", "upload", "utf-8"),
            new StringPart("filename", filename, "utf-8"), new StringPart("comment", description, "utf-8"),
            new StringPart("watch", "true", "utf-8"), new StringPart("ignorewarnings", "true", "utf-8"),
            new StringPart("token", token, "utf-8"), new StringPart("format", "xml", "utf-8"),
            new FilePart("file", new ByteArrayPartSource(filename, data), "image/jpeg", "utf-8"), };
    httppost.setEntity(new MultipartEntity(nvps, httppost.getParams()));

    response = getHttpDocument(httpclient, httppost);

    root = response.getDocumentElement();

    // First, check for errors.
    if (doesResponseHaveError(root)) {
        throw new WikiException(getErrorTextId(findErrorCode(root)));
    }
}