Example usage for org.apache.http.entity.mime HttpMultipartMode STRICT

List of usage examples for org.apache.http.entity.mime HttpMultipartMode STRICT

Introduction

In this page you can find the example usage for org.apache.http.entity.mime HttpMultipartMode STRICT.

Prototype

HttpMultipartMode STRICT

To view the source code for org.apache.http.entity.mime HttpMultipartMode STRICT.

Click Source Link

Usage

From source file:com.jayway.restassured.config.HttpClientConfig.java

/**
 * Creates a new  HttpClientConfig instance with the parameters defined by the <code>httpClientParams</code>.
 *//*from w  w  w  . j  a va 2s.  c o m*/
public HttpClientConfig(Map<String, ?> httpClientParams) {
    this(defaultHttpClientFactory(), httpClientParams, HttpMultipartMode.STRICT,
            SHOULD_REUSE_HTTP_CLIENT_INSTANCE_BY_DEFAULT, NO_HTTP_CLIENT, true);
}

From source file:net.kidlogger.kidlogger.SendTestReport.java

private void sendPOST() {
    File fs = getFile();//www .j  a v a 2  s.c  o  m
    Date now = new Date();
    String fileDate = String.format("%td/%tm/%tY %tT", now, now, now, now);
    String devField = Settings.getDeviceField(context);
    if (devField.equals("undefined") || devField.equals(""))
        return;
    try {
        HttpClient client = new DefaultHttpClient();
        String postUrl = context.getString(R.string.upload_link);
        //String postUrl = "http://10.0.2.2/denwer/";
        HttpPost post = new HttpPost(postUrl);
        FileBody bin = new FileBody(fs, "text/html", fs.getName());
        StringBody sb1 = new StringBody(devField);
        StringBody sb2 = new StringBody("HTML");
        StringBody sb3 = new StringBody("Andriod_2_2");
        StringBody sb4 = new StringBody("1.0");
        StringBody sb5 = new StringBody(fileDate);

        MultipartEntity reqEntity = new MultipartEntity(HttpMultipartMode.STRICT);
        reqEntity.addPart("file", bin);
        reqEntity.addPart("device", sb1);
        reqEntity.addPart("content", sb2);
        reqEntity.addPart("client-ver", sb3);
        reqEntity.addPart("app-ver", sb4);
        reqEntity.addPart("client-date-time", sb5);

        post.setEntity(reqEntity);
        HttpResponse response = client.execute(post);
        HttpEntity resEntity = response.getEntity();
        if (resEntity != null) {
            String pStatus = EntityUtils.toString(resEntity);
            if (pStatus.equalsIgnoreCase("Ok")) {
                fs.delete();
                testRes.setText("Response: " + pStatus);
            } else {
                //Log.i("sendPOST", pStatus);
            }
            testRes.setText("Response: " + pStatus);
            //Log.i("sendPOST", "Response: " + pStatus);
        }
    } catch (Exception e) {
        //Log.i("sendPOST", e.toString());
    }
}

From source file:org.apache.manifoldcf.agents.output.solr.ModifiedHttpMultipart.java

/**
 * Creates an instance with the specified settings.
 * Mode is set to {@link HttpMultipartMode#STRICT}
 *
 * @param subType mime subtype - must not be {@code null}
 * @param charset the character set to use. May be {@code null}, in which case {@link MIME#DEFAULT_CHARSET} - i.e. US-ASCII - is used.
 * @param boundary to use  - must not be {@code null}
 * @throws IllegalArgumentException if charset is null or boundary is null
 *//*from  w  ww  .j a  v a  2  s .  c o  m*/
public ModifiedHttpMultipart(final String subType, final Charset charset, final String boundary) {
    this(subType, charset, boundary, HttpMultipartMode.STRICT);
}

From source file:edu.si.services.sidora.rest.batch.BatchServiceTest.java

@Test
public void newBatchRequest_addResourceObjects_Test() throws Exception {

    String resourceListXML = FileUtils
            .readFileToString(new File("src/test/resources/test-data/batch-test-files/audio/audioFiles.xml"));

    String expectedHTTPResponseBody = "<?xml version=\"1.0\" encoding=\"UTF-8\" standalone=\"yes\"?>\n"
            + "<Batch>\n" + "    <ParentPID>" + parentPid + "</ParentPID>\n" + "    <CorrelationID>"
            + correlationId + "</CorrelationID>\n" + "</Batch>\n";

    BatchRequestResponse expectedCamelResponseBody = new BatchRequestResponse();
    expectedCamelResponseBody.setParentPID(parentPid);
    expectedCamelResponseBody.setCorrelationId(correlationId);

    MockEndpoint mockEndpoint = getMockEndpoint("mock:result");
    mockEndpoint.expectedMessageCount(1);

    context.getComponent("sql", SqlComponent.class).setDataSource(db);
    context.getRouteDefinition("BatchProcessResources").autoStartup(false);

    //Configure and use adviceWith to mock for testing purpose
    context.getRouteDefinition("BatchProcessAddResourceObjects").adviceWith(context,
            new AdviceWithRouteBuilder() {
                @Override/*  ww w .j a v a 2  s.  co m*/
                public void configure() throws Exception {
                    weaveById("httpGetResourceList").replace().setBody(simple(resourceListXML));

                    weaveByToString(".*bean:batchRequestControllerBean.*").replace().setHeader("correlationId",
                            simple(correlationId));

                    weaveAddLast().to("mock:result");

                }
            });

    HttpPost post = new HttpPost(BASE_URL + "/addResourceObjects/" + parentPid);

    MultipartEntityBuilder builder = MultipartEntityBuilder.create().setMode(HttpMultipartMode.STRICT);

    // Add filelist xml URL upload
    builder.addTextBody("resourceFileList", resourceFileList, ContentType.TEXT_PLAIN);
    // Add metadata xml file URL upload
    builder.addTextBody("ds_metadata", ds_metadata, ContentType.TEXT_PLAIN);
    // Add sidora xml URL upload
    builder.addTextBody("ds_sidora", ds_sidora, ContentType.TEXT_PLAIN);
    // Add association xml URL upload
    builder.addTextBody("association", association, ContentType.TEXT_PLAIN);
    // Add resourceOwner string
    builder.addTextBody("resourceOwner", resourceOwner, ContentType.TEXT_PLAIN);

    post.setEntity(builder.build());

    HttpResponse response = httpClient.execute(post);
    assertEquals(200, response.getStatusLine().getStatusCode());
    String responseBody = EntityUtils.toString(response.getEntity());
    log.debug("======================== [ RESPONSE ] ========================\n" + responseBody);

    assertEquals(expectedHTTPResponseBody, responseBody);

    log.debug("===============[ DB Requests ]================\n{}",
            jdbcTemplate.queryForList("select * from sidora.camelBatchRequests"));
    log.debug("===============[ DB Resources ]===============\n{}",
            jdbcTemplate.queryForList("select * from sidora.camelBatchResources"));

    BatchRequestResponse camelResultBody = (BatchRequestResponse) mockEndpoint.getExchanges().get(0).getIn()
            .getBody();

    assertIsInstanceOf(BatchRequestResponse.class, camelResultBody);
    assertEquals(camelResultBody.getParentPID(), parentPid);
    assertEquals(camelResultBody.getCorrelationId(), correlationId);

    assertMockEndpointsSatisfied();

}

From source file:ua.pp.msk.gradle.http.Client.java

public boolean upload(NexusConf nc) throws ArtifactPromotionException {
    boolean result = false;
    String possibleFailReason = "Unknown";
    try {/*from   w  w  w. ja va  2s  .com*/
        HttpPost httpPost = new HttpPost(targetUrl.toString());

        MultipartEntity me = new MultipartEntity(HttpMultipartMode.STRICT);
        //            FormBodyPart fbp = new FormBodyPart("form", new StringBody("check it"));
        //            fbp.addField("r", nc.getRepository());
        //            fbp.addField("hasPom", "" + nc.isHasPom());
        //            fbp.addField("e", nc.getExtension());
        //            fbp.addField("g", nc.getGroup());
        //            fbp.addField("a", nc.getArtifact());
        //            fbp.addField("v", nc.getVersion());
        //            fbp.addField("p", nc.getPackaging());
        //            me.addPart(fbp);
        File rpmFile = new File(nc.getFile());
        ContentBody cb = new FileBody(rpmFile);
        me.addPart("p", new StringBody(nc.getPackaging()));
        me.addPart("e", new StringBody(nc.getExtension()));
        me.addPart("r", new StringBody(nc.getRepository()));
        me.addPart("g", new StringBody(nc.getGroup()));
        me.addPart("a", new StringBody(nc.getArtifact()));
        me.addPart("v", new StringBody(nc.getVersion()));
        me.addPart("c", new StringBody(nc.getClassifier()));
        me.addPart("file", cb);

        httpPost.setHeader("User-Agent", userAgent);
        httpPost.setEntity(me);

        logger.debug("Sending request");
        HttpResponse postResponse = client.execute(httpPost, context);
        logger.debug("Status line: " + postResponse.getStatusLine().toString());
        int statusCode = postResponse.getStatusLine().getStatusCode();

        HttpEntity entity = postResponse.getEntity();

        try (BufferedReader bufReader = new BufferedReader(new InputStreamReader(entity.getContent()))) {
            StringBuilder fsb = new StringBuilder();
            bufReader.lines().forEach(e -> {
                logger.debug(e);
                fsb.append(e);
                fsb.append("\n");
            });
            possibleFailReason = fsb.toString();
        } catch (IOException ex) {
            logger.warn("Cannot get entity response", ex);
        }

        switch (statusCode) {
        case 200:
            logger.debug("Got a successful http response " + postResponse.getStatusLine());
            result = true;
            break;
        case 201:
            logger.debug("Created! Got a successful http response " + postResponse.getStatusLine());
            result = true;
            break;
        case 401:
            throw new BadCredentialsException(
                    "Bad credentials. Response status: " + postResponse.getStatusLine());
        default:
            throw new ResponseException(
                    String.format("Response is not OK. Response status: %s\n\tPossible reason: %s",
                            postResponse.getStatusLine(), possibleFailReason));
        }

        EntityUtils.consume(entity);

    } catch (UnsupportedEncodingException ex) {
        logger.error("Encoding is unsuported ", ex);
        throw new ArtifactPromotionException("Encoding is unsuported " + ex.getMessage());
    } catch (IOException ex) {
        logger.error("Got IO excepption ", ex);
        throw new ArtifactPromotionException("Input/Output error " + ex.getMessage());
    } catch (ResponseException | BadCredentialsException ex) {
        logger.error("Cannot upload artifact", ex);
        throw new ArtifactPromotionException("Cannot upload artifact " + ex.getMessage());
    }
    return result;
}

From source file:net.yama.android.managers.connection.OAuthConnectionManager.java

/**
 * Special request for photo upload since OAuth doesn't handle multipart/form-data
 *//*from   w  w w .java2s.c om*/
public String uploadPhoto(WritePhotoRequest request) throws ApplicationException {

    String responseString = null;
    try {
        OAuthAccessor accessor = new OAuthAccessor(OAuthConnectionManager.consumer);
        accessor.accessToken = ConfigurationManager.instance.getAccessToken();
        accessor.tokenSecret = ConfigurationManager.instance.getAccessTokenSecret();

        String tempImagePath = request.getParameterMap().remove(Constants.TEMP_IMAGE_FILE_PATH);
        String eventId = request.getParameterMap().remove(Constants.EVENT_ID_KEY);

        ArrayList<Map.Entry<String, String>> params = new ArrayList<Map.Entry<String, String>>();
        convertRequestParamsToOAuth(params, request.getParameterMap());
        OAuthMessage message = new OAuthMessage(request.getMethod(), request.getRequestURL(), params);
        message.addRequiredParameters(accessor);
        List<Map.Entry<String, String>> oAuthParams = message.getParameters();
        String url = OAuth.addParameters(request.getRequestURL(), oAuthParams);

        HttpPost post = new HttpPost(url);
        File photoFile = new File(tempImagePath);
        FileBody photoContentBody = new FileBody(photoFile);
        StringBody eventIdBody = new StringBody(eventId);

        HttpClient client = new DefaultHttpClient();
        MultipartEntity reqEntity = new MultipartEntity(HttpMultipartMode.STRICT);
        reqEntity.addPart(Constants.PHOTO, photoContentBody);
        reqEntity.addPart(Constants.EVENT_ID_KEY, eventIdBody);
        post.setEntity(reqEntity);

        HttpResponse response = client.execute(post);
        HttpEntity resEntity = response.getEntity();
        responseString = EntityUtils.toString(resEntity);

    } catch (Exception e) {
        Log.e("OAuthConnectionManager", "Exception in uploadPhoto()", e);
        throw new ApplicationException(e);
    }

    return responseString;
}

From source file:org.opendatakit.aggregate.externalservice.OhmageJsonServer.java

/**
 * Uploads a set of submissions to the ohmage system.
 *
 * @throws IOException//from w  w w. java2s  .co m
 * @throws ClientProtocolException
 * @throws ODKExternalServiceException
 * @throws URISyntaxException
 */
public void uploadSurveys(List<OhmageJsonTypes.Survey> surveys, Map<UUID, ByteArrayBody> photos,
        CallingContext cc)
        throws ClientProtocolException, IOException, ODKExternalServiceException, URISyntaxException {

    MultipartEntity reqEntity = new MultipartEntity(HttpMultipartMode.STRICT, null, UTF_CHARSET);
    // emit the configured publisher parameters if the values are non-empty...
    String value;
    value = getOhmageCampaignUrn();
    if (value != null && value.length() != 0) {
        StringBody campaignUrn = new StringBody(getOhmageCampaignUrn(), UTF_CHARSET);
        reqEntity.addPart("campaign_urn", campaignUrn);
    }
    value = getOhmageCampaignCreationTimestamp();
    if (value != null && value.length() != 0) {
        StringBody campaignCreationTimestamp = new StringBody(getOhmageCampaignCreationTimestamp(),
                UTF_CHARSET);
        reqEntity.addPart("campaign_creation_timestamp", campaignCreationTimestamp);
    }
    value = getOhmageUsername();
    if (value != null && value.length() != 0) {
        StringBody user = new StringBody(getOhmageUsername(), UTF_CHARSET);
        reqEntity.addPart("user", user);
    }
    value = getOhmageHashedPassword();
    if (value != null && value.length() != 0) {
        StringBody hashedPassword = new StringBody(getOhmageHashedPassword(), UTF_CHARSET);
        reqEntity.addPart("passowrd", hashedPassword);
    }
    // emit the client identity and the json representation of the survey...
    StringBody clientParam = new StringBody(cc.getServerURL());
    reqEntity.addPart("client", clientParam);
    StringBody surveyData = new StringBody(gson.toJson(surveys));
    reqEntity.addPart("survey", surveyData);

    // emit the file streams for all the media attachments
    for (Entry<UUID, ByteArrayBody> entry : photos.entrySet()) {
        reqEntity.addPart(entry.getKey().toString(), entry.getValue());
    }

    HttpResponse response = super.sendHttpRequest(POST, getServerUrl(), reqEntity, null, cc);
    String responseString = WebUtils.readResponse(response);
    int statusCode = response.getStatusLine().getStatusCode();

    if (statusCode == HttpServletResponse.SC_UNAUTHORIZED) {
        throw new ODKExternalServiceCredentialsException(
                "failure from server: " + statusCode + " response: " + responseString);
    } else if (statusCode >= 300) {
        throw new ODKExternalServiceException(
                "failure from server: " + statusCode + " response: " + responseString);
    }
}

From source file:org.trancecode.xproc.step.RequestParser.java

private MultipartEntity parseMultipart(final XdmNode requestNode, final Processor processor) {
    final XdmNode child = SaxonAxis.childElement(requestNode, XProcXmlModel.Elements.MULTIPART);
    if (child != null) {
        final String contentTypeAtt = child.getAttributeValue(XProcXmlModel.Attributes.CONTENT_TYPE);
        final String contentType = Strings.isNullOrEmpty(contentTypeAtt) ? DEFAULT_MULTIPART_TYPE
                : contentTypeAtt;/*from ww  w . j  a v a2s .c o m*/
        final String boundary = child.getAttributeValue(XProcXmlModel.Attributes.BOUNDARY);
        if (StringUtils.startsWith(boundary, "--")) {
            throw XProcExceptions.xc0002(requestNode);
        }
        final MultipartEntity reqEntity = new MultipartEntity(HttpMultipartMode.STRICT, boundary,
                Charset.forName("UTF-8")) {
            @Override
            protected String generateContentType(final String boundary, final Charset charset) {
                final StringBuilder buffer = new StringBuilder();
                buffer.append(contentType).append("; boundary=").append(boundary);
                return buffer.toString();
            }
        };
        final Iterable<XdmNode> bodies = SaxonAxis.childElements(child, XProcXmlModel.Elements.BODY);
        for (final XdmNode body : bodies) {
            final FormBodyPart contentBody = getContentBody(body, processor);
            if (contentBody != null) {
                reqEntity.addPart(contentBody);
            }
        }

        return reqEntity;
    }
    return null;
}

From source file:org.wso2.am.integration.tests.other.InvalidAuthTokenLargePayloadTestCase.java

/**
 * Upload a file to the given URL/*from  w w w .j  av  a  2  s . c om*/
 *
 * @param endpointUrl URL to be file upload
 * @param fileName    Name of the file to be upload
 * @throws IOException throws if connection issues occurred
 */
private HttpResponse uploadFile(String endpointUrl, File fileName, Map<String, String> headers)
        throws IOException {
    //open import API url connection and deploy the exported API
    URL url = new URL(endpointUrl);
    HttpURLConnection connection = (HttpURLConnection) url.openConnection();
    connection.setDoOutput(true);
    connection.setRequestMethod("POST");

    FileBody fileBody = new FileBody(fileName);
    MultipartEntity multipartEntity = new MultipartEntity(HttpMultipartMode.STRICT);
    multipartEntity.addPart("file", fileBody);

    connection.setRequestProperty("Content-Type", multipartEntity.getContentType().getValue());
    //setting headers
    if (headers != null && headers.size() > 0) {
        Iterator<String> itr = headers.keySet().iterator();
        while (itr.hasNext()) {
            String key = itr.next();
            if (key != null) {
                connection.setRequestProperty(key, headers.get(key));
            }
        }
        for (String key : headers.keySet()) {
            connection.setRequestProperty(key, headers.get(key));
        }
    }

    OutputStream out = connection.getOutputStream();
    try {
        multipartEntity.writeTo(out);
    } finally {
        out.close();
    }
    int status = connection.getResponseCode();
    BufferedReader read = new BufferedReader(new InputStreamReader(connection.getInputStream()));
    String temp;
    StringBuilder responseMsg = new StringBuilder();
    while ((temp = read.readLine()) != null) {
        responseMsg.append(temp);
    }
    HttpResponse response = new HttpResponse(responseMsg.toString(), status);
    return response;
}