Search in sources :

Example 11 with StringPart

use of org.apache.commons.httpclient.methods.multipart.StringPart in project twitter-2-weibo by rjyo.

the class HttpClient method multPartURL.

/**
	 * 支持multipart方式上传图片
	 * 
	 */
public Response multPartURL(String url, PostParameter[] params, ImageItem item) throws WeiboException {
    PostMethod postMethod = new PostMethod(url);
    try {
        Part[] parts = null;
        if (params == null) {
            parts = new Part[1];
        } else {
            parts = new Part[params.length + 1];
        }
        if (params != null) {
            int i = 0;
            for (PostParameter entry : params) {
                parts[i++] = new StringPart(entry.getName(), (String) entry.getValue());
            }
            parts[parts.length - 1] = new ByteArrayPart(item.getContent(), item.getName(), item.getContentType());
        }
        postMethod.setRequestEntity(new MultipartRequestEntity(parts, postMethod.getParams()));
        return httpRequest(postMethod);
    } catch (Exception ex) {
        throw new WeiboException(ex.getMessage(), ex, -1);
    }
}
Also used : WeiboException(weibo4j.model.WeiboException) PostParameter(weibo4j.model.PostParameter) PostMethod(org.apache.commons.httpclient.methods.PostMethod) StringPart(org.apache.commons.httpclient.methods.multipart.StringPart) FilePart(org.apache.commons.httpclient.methods.multipart.FilePart) Part(org.apache.commons.httpclient.methods.multipart.Part) StringPart(org.apache.commons.httpclient.methods.multipart.StringPart) MultipartRequestEntity(org.apache.commons.httpclient.methods.multipart.MultipartRequestEntity) JSONException(weibo4j.org.json.JSONException) IOException(java.io.IOException) WeiboException(weibo4j.model.WeiboException)

Example 12 with StringPart

use of org.apache.commons.httpclient.methods.multipart.StringPart in project twitter-2-weibo by rjyo.

the class HttpClient method multPartURL.

public Response multPartURL(String fileParamName, String url, PostParameter[] params, File file, boolean authenticated) throws WeiboException {
    PostMethod postMethod = new PostMethod(url);
    try {
        Part[] parts = null;
        if (params == null) {
            parts = new Part[1];
        } else {
            parts = new Part[params.length + 1];
        }
        if (params != null) {
            int i = 0;
            for (PostParameter entry : params) {
                parts[i++] = new StringPart(entry.getName(), (String) entry.getValue());
            }
        }
        FilePart filePart = new FilePart(fileParamName, file.getName(), file, new MimetypesFileTypeMap().getContentType(file), "UTF-8");
        filePart.setTransferEncoding("binary");
        parts[parts.length - 1] = filePart;
        postMethod.setRequestEntity(new MultipartRequestEntity(parts, postMethod.getParams()));
        return httpRequest(postMethod);
    } catch (Exception ex) {
        throw new WeiboException(ex.getMessage(), ex, -1);
    }
}
Also used : MimetypesFileTypeMap(javax.activation.MimetypesFileTypeMap) WeiboException(weibo4j.model.WeiboException) PostParameter(weibo4j.model.PostParameter) PostMethod(org.apache.commons.httpclient.methods.PostMethod) StringPart(org.apache.commons.httpclient.methods.multipart.StringPart) FilePart(org.apache.commons.httpclient.methods.multipart.FilePart) Part(org.apache.commons.httpclient.methods.multipart.Part) StringPart(org.apache.commons.httpclient.methods.multipart.StringPart) MultipartRequestEntity(org.apache.commons.httpclient.methods.multipart.MultipartRequestEntity) FilePart(org.apache.commons.httpclient.methods.multipart.FilePart) JSONException(weibo4j.org.json.JSONException) IOException(java.io.IOException) WeiboException(weibo4j.model.WeiboException)

Example 13 with StringPart

use of org.apache.commons.httpclient.methods.multipart.StringPart in project jaggery by wso2.

the class XMLHttpRequestHostObject method send.

private void send(Context cx, Object obj) throws ScriptException {
    final HttpMethodBase method;
    if ("GET".equalsIgnoreCase(methodName)) {
        method = new GetMethod(this.url);
    } else if ("HEAD".equalsIgnoreCase(methodName)) {
        method = new HeadMethod(this.url);
    } else if ("POST".equalsIgnoreCase(methodName)) {
        PostMethod post = new PostMethod(this.url);
        if (obj instanceof FormDataHostObject) {
            FormDataHostObject fd = ((FormDataHostObject) obj);
            List<Part> parts = new ArrayList<Part>();
            for (Map.Entry<String, String> entry : fd) {
                parts.add(new StringPart(entry.getKey(), entry.getValue()));
            }
            post.setRequestEntity(new MultipartRequestEntity(parts.toArray(new Part[parts.size()]), post.getParams()));
        } else {
            String content = getRequestContent(obj);
            if (content != null) {
                post.setRequestEntity(new InputStreamRequestEntity(new ByteArrayInputStream(content.getBytes())));
            }
        }
        method = post;
    } else if ("PUT".equalsIgnoreCase(methodName)) {
        PutMethod put = new PutMethod(this.url);
        String content = getRequestContent(obj);
        if (content != null) {
            put.setRequestEntity(new InputStreamRequestEntity(new ByteArrayInputStream(content.getBytes())));
        }
        method = put;
    } else if ("DELETE".equalsIgnoreCase(methodName)) {
        method = new DeleteMethod(this.url);
    } else if ("TRACE".equalsIgnoreCase(methodName)) {
        method = new TraceMethod(this.url);
    } else if ("OPTIONS".equalsIgnoreCase(methodName)) {
        method = new OptionsMethod(this.url);
    } else {
        throw new ScriptException("Unknown HTTP method : " + methodName);
    }
    for (Header header : requestHeaders) {
        method.addRequestHeader(header);
    }
    if (username != null) {
        httpClient.getState().setCredentials(AuthScope.ANY, new UsernamePasswordCredentials(username, password));
    }
    this.method = method;
    final XMLHttpRequestHostObject xhr = this;
    if (async) {
        updateReadyState(cx, xhr, LOADING);
        final ContextFactory factory = cx.getFactory();
        final ExecutorService es = Executors.newSingleThreadExecutor();
        es.submit(new Callable() {

            public Object call() throws Exception {
                Context ctx = RhinoEngine.enterContext(factory);
                try {
                    executeRequest(ctx, xhr);
                } catch (ScriptException e) {
                    log.error(e.getMessage(), e);
                } finally {
                    es.shutdown();
                    RhinoEngine.exitContext();
                }
                return null;
            }
        });
    } else {
        executeRequest(cx, xhr);
    }
}
Also used : ArrayList(java.util.ArrayList) StringPart(org.apache.commons.httpclient.methods.multipart.StringPart) Callable(java.util.concurrent.Callable) ScriptException(org.jaggeryjs.scriptengine.exceptions.ScriptException) MultipartRequestEntity(org.apache.commons.httpclient.methods.multipart.MultipartRequestEntity) IOException(java.io.IOException) GeneralSecurityException(java.security.GeneralSecurityException) ScriptException(org.jaggeryjs.scriptengine.exceptions.ScriptException) ByteArrayInputStream(java.io.ByteArrayInputStream) StringPart(org.apache.commons.httpclient.methods.multipart.StringPart) Part(org.apache.commons.httpclient.methods.multipart.Part) ExecutorService(java.util.concurrent.ExecutorService) Map(java.util.Map)

Example 14 with StringPart

use of org.apache.commons.httpclient.methods.multipart.StringPart in project zm-mailbox by Zimbra.

the class TestFileUpload method testAdminUploadWithCsrfInFormField.

@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);
    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);
    Assert.assertEquals("This request should succeed. Getting status code " + statusCode, HttpStatus.SC_OK, statusCode);
    String resp = post.getResponseBodyAsString();
    Assert.assertNotNull("Response should not be empty", resp);
    Assert.assertTrue("Incorrect HTML response", resp.contains(RESP_STR));
}
Also used : PostMethod(org.apache.commons.httpclient.methods.PostMethod) HeaderElement(org.apache.commons.httpclient.HeaderElement) Element(com.zimbra.common.soap.Element) StringPart(org.apache.commons.httpclient.methods.multipart.StringPart) HttpState(org.apache.commons.httpclient.HttpState) MultipartRequestEntity(org.apache.commons.httpclient.methods.multipart.MultipartRequestEntity) FilePart(org.apache.commons.httpclient.methods.multipart.FilePart) ByteArrayPartSource(org.apache.commons.httpclient.methods.multipart.ByteArrayPartSource) ServiceException(com.zimbra.common.service.ServiceException) StringPart(org.apache.commons.httpclient.methods.multipart.StringPart) FilePart(org.apache.commons.httpclient.methods.multipart.FilePart) Part(org.apache.commons.httpclient.methods.multipart.Part) HttpClient(org.apache.commons.httpclient.HttpClient) SoapHttpTransport(com.zimbra.common.soap.SoapHttpTransport) Test(org.junit.Test)

Example 15 with StringPart

use of org.apache.commons.httpclient.methods.multipart.StringPart in project sling by apache.

the class SlingIntegrationTestClient method uploadToFileNodes.

/** Upload multiple files to file node structures */
public void uploadToFileNodes(String url, File[] localFiles, String[] fieldNames, String[] typeHints) throws IOException {
    List<Part> partsList = new ArrayList<Part>();
    for (int i = 0; i < localFiles.length; i++) {
        Part filePart = new FilePart(fieldNames[i], localFiles[i]);
        partsList.add(filePart);
        if (typeHints != null) {
            Part typeHintPart = new StringPart(fieldNames[i] + "@TypeHint", typeHints[i]);
            partsList.add(typeHintPart);
        }
    }
    final Part[] parts = partsList.toArray(new Part[partsList.size()]);
    final PostMethod post = new PostMethod(url);
    post.setFollowRedirects(false);
    post.setRequestEntity(new MultipartRequestEntity(parts, post.getParams()));
    final int expected = 200;
    final int status = httpClient.executeMethod(post);
    if (status != expected) {
        throw new HttpStatusCodeException(expected, status, "POST", HttpTestBase.getResponseBodyAsStream(post, 0));
    }
}
Also used : PostMethod(org.apache.commons.httpclient.methods.PostMethod) StringPart(org.apache.commons.httpclient.methods.multipart.StringPart) FilePart(org.apache.commons.httpclient.methods.multipart.FilePart) Part(org.apache.commons.httpclient.methods.multipart.Part) ArrayList(java.util.ArrayList) StringPart(org.apache.commons.httpclient.methods.multipart.StringPart) MultipartRequestEntity(org.apache.commons.httpclient.methods.multipart.MultipartRequestEntity) FilePart(org.apache.commons.httpclient.methods.multipart.FilePart)

Aggregations

MultipartRequestEntity (org.apache.commons.httpclient.methods.multipart.MultipartRequestEntity)22 Part (org.apache.commons.httpclient.methods.multipart.Part)22 StringPart (org.apache.commons.httpclient.methods.multipart.StringPart)22 PostMethod (org.apache.commons.httpclient.methods.PostMethod)19 FilePart (org.apache.commons.httpclient.methods.multipart.FilePart)19 IOException (java.io.IOException)7 ArrayList (java.util.ArrayList)7 HttpClient (org.apache.commons.httpclient.HttpClient)7 File (java.io.File)6 MojoExecutionException (org.apache.maven.plugin.MojoExecutionException)4 Test (org.junit.Test)4 Map (java.util.Map)3 UsernamePasswordCredentials (org.apache.commons.httpclient.UsernamePasswordCredentials)3 ByteArrayPartSource (org.apache.commons.httpclient.methods.multipart.ByteArrayPartSource)3 FilePartSource (org.apache.commons.httpclient.methods.multipart.FilePartSource)3 HttpMethodParams (org.apache.commons.httpclient.params.HttpMethodParams)3 ByteArrayInputStream (java.io.ByteArrayInputStream)2 RepositoryException (org.apache.sling.ide.transport.RepositoryException)2 PostParameter (weibo4j.model.PostParameter)2 WeiboException (weibo4j.model.WeiboException)2