Example usage for org.apache.http.entity ContentType create

List of usage examples for org.apache.http.entity ContentType create

Introduction

In this page you can find the example usage for org.apache.http.entity ContentType create.

Prototype

private static ContentType create(HeaderElement headerElement) 

Source Link

Usage

From source file:nl.uva.mediamosa.impl.MediaMosaImpl.java

/**
 * @param postRequest/* w  w  w  .  ja v  a2  s  . c om*/
 * @param postParams
 * @return
 * @throws java.io.IOException
 */
public Response doPostRequest(String uploadHost, String postRequest, String postParams, InputStream stream,
        String mimeType, String filename) throws IOException {
    HttpPost httpPost = new HttpPost(uploadHost + postRequest);

    MultipartEntityBuilder mpBuilder = MultipartEntityBuilder.create();
    mpBuilder.addBinaryBody("file", stream, ContentType.create(mimeType), filename);

    List<NameValuePair> nvps = URLEncodedUtils.parse(postParams, Charset.forName("UTF-8"));
    for (NameValuePair nameValuePair : nvps) {
        mpBuilder.addTextBody(nameValuePair.getName(), nameValuePair.getValue());
    }
    httpPost.setEntity(mpBuilder.build());

    return UnmarshallUtil.unmarshall(getXmlTransformedResponse(httpPost));
}

From source file:me.buom.shiro.test.AppTest.java

@Test
@Repeat(times = 3, warmUp = 1)//from w  w w  .j  ava2  s .com
public void test_admin() throws Exception {

    URL url = new URL(baseUrl.toExternalForm() + "admin");
    HttpPost method = new HttpPost(url.toURI());

    String contentType = "application/json; charset=utf-8";
    String entity = "lady gaga";
    Header[] headers = buildHeader(ApiKey.ADMIN, method, contentType, entity);

    method.setHeaders(headers);
    method.setEntity(new StringEntity(entity, ContentType.create(contentType)));

    HttpResponse execute = client.execute(method);
    StatusLine statusLine = execute.getStatusLine();

    printResponse(execute);
    printHeader(execute);

    Assert.assertFalse(statusLine.getStatusCode() != 200);
}

From source file:org.eclipse.rdf4j.http.server.ProtocolTest.java

/**
 * Checks that the server accepts a direct POST with a content type of "application/sparql-update".
 *///from w w w . j  a  va  2  s. c o m
@Test
public void testUpdateDirect_POST() throws Exception {
    String query = "delete where { <monkey:pod> ?p ?o }";
    String location = Protocol.getStatementsLocation(TestServer.REPOSITORY_URL);

    CloseableHttpClient httpclient = HttpClients.createDefault();
    HttpPost post = new HttpPost(location);
    HttpEntity entity = new StringEntity(query, ContentType.create(Protocol.SPARQL_UPDATE_MIME_TYPE));
    post.setEntity(entity);

    CloseableHttpResponse response = httpclient.execute(post);

    System.out.println("Update Direct Post Status: " + response.getStatusLine());
    int statusCode = response.getStatusLine().getStatusCode();
    assertEquals(true, statusCode >= 200 && statusCode < 400);
}

From source file:com.baidu.qa.service.test.client.SoapReqImpl.java

private static String sendSoap(String hosturl, String ip, int port, String action, String method, String xml,
        boolean isHttps) throws Exception {
    if (isHttps) {
        return sendSoapViaHttps(hosturl, ip, port, action, method, xml);
    }/*www .ja va  2 s.c  om*/

    HttpParams params = new SyncBasicHttpParams();
    HttpProtocolParams.setVersion(params, HttpVersion.HTTP_1_1);
    HttpProtocolParams.setContentCharset(params, "UTF-8");// must be UTF-8
    HttpProtocolParams.setUserAgent(params, "itest-by-HttpCore/4.2");

    HttpProcessor httpproc = new ImmutableHttpProcessor(new HttpRequestInterceptor[] {
            // Required protocol interceptors
            new RequestContent(), new RequestTargetHost(),
            // Recommended protocol interceptors
            new RequestConnControl(), new RequestUserAgent(), new RequestExpectContinue() });

    HttpRequestExecutor httpexecutor = new HttpRequestExecutor();

    HttpContext context = new BasicHttpContext(null);

    // log.info("ip:port - " + ip + ":" + port );
    HttpHost host = new HttpHost(ip, port);// TODO

    DefaultHttpClientConnection conn = new DefaultHttpClientConnection();
    conn.setSocketTimeout(10000);
    HttpConnectionParams.setSoTimeout(params, 10000);
    ConnectionReuseStrategy connStrategy = new DefaultConnectionReuseStrategy();

    context.setAttribute(ExecutionContext.HTTP_CONNECTION, conn);
    context.setAttribute(ExecutionContext.HTTP_TARGET_HOST, host);

    String res = null;

    try {
        // HttpEntity requestBody = new
        // ByteArrayEntity(xml.getBytes("UTF-8"));// TODO
        byte[] b = xml.getBytes("UTF-8"); // must be UTF-8
        InputStream is = new ByteArrayInputStream(b, 0, b.length);

        HttpEntity requestBody = new InputStreamEntity(is, b.length,
                ContentType.create("text/xml;charset=UTF-8"));// must be
        // UTF-8

        // .create("application/xop+xml; charset=UTF-8; type=\"text/xml\""));//
        // TODO

        // RequestEntity re = new InputStreamRequestEntity(is, b.length,
        // "application/xop+xml; charset=UTF-8; type=\"text/xml\"");
        // postmethod.setRequestEntity(re);

        if (!conn.isOpen()) {
            Socket socket = new Socket(host.getHostName(), host.getPort());
            conn.bind(socket, params);
        }
        BasicHttpEntityEnclosingRequest request = new BasicHttpEntityEnclosingRequest("POST", action);

        // add the 3 headers below
        request.addHeader("Accept-Encoding", "gzip,deflate");
        request.addHeader("SOAPAction", hosturl + action + method);// SOAP action
        request.addHeader("uuid", "itest");// for editor token of DR-Api

        request.setEntity(requestBody);
        log.info(">> Request URI: " + request.getRequestLine().getUri());

        request.setParams(params);
        httpexecutor.preProcess(request, httpproc, context);
        HttpResponse response = httpexecutor.execute(request, conn, context);
        response.setParams(params);
        httpexecutor.postProcess(response, httpproc, context);

        log.info("<< Response: " + response.getStatusLine());

        String contentEncoding = null;
        Header ce = response.getEntity().getContentEncoding();
        if (ce != null) {
            contentEncoding = ce.getValue();
        }

        if (contentEncoding != null && contentEncoding.indexOf("gzip") != -1) {
            GZIPInputStream gzipin = new GZIPInputStream(response.getEntity().getContent());
            Scanner in = new Scanner(new InputStreamReader(gzipin, "UTF-8"));
            StringBuilder sb = new StringBuilder();
            while (in.hasNextLine()) {
                sb.append(in.nextLine()).append(System.getProperty("line.separator"));
            }
            res = sb.toString();
        } else {
            res = EntityUtils.toString(response.getEntity(), "UTF-8");
        }
        log.info(res);

        log.info("==============");
        if (!connStrategy.keepAlive(response, context)) {
            conn.close();
        } else {
            log.info("Connection kept alive...");
        }
    } finally {
        try {
            conn.close();
        } catch (IOException e) {
        }
    }
    return res;
}

From source file:org.apache.streams.components.http.processor.SimpleHTTPPostProcessor.java

/**
 Override this to add parameters to the request.
 *//*from w  w w .j  ava 2s  .c om*/
protected HttpEntity preparePayload(StreamsDatum entry) {
    return new StringEntity("{}", ContentType.create("application/json"));
}

From source file:org.jenkinsci.test.acceptance.update_center.MockUpdateCenter.java

public void ensureRunning() {
    if (original != null) {
        return;/*from   w  ww  . j a  v a  2  s. c om*/
    }
    // TODO this will likely not work on arbitrary controllers, so perhaps limit to the default WinstoneController
    Jenkins jenkins = injector.getInstance(Jenkins.class);
    List<String> sites = new UpdateCenter(jenkins).getJson("tree=sites[url]").findValuesAsText("url");
    if (sites.size() != 1) {
        // TODO ideally it would rather delegate to all of them, but that implies deprecating CachedUpdateCenterMetadataLoader.url and using whatever site(s) Jenkins itself specifies
        LOGGER.log(Level.WARNING, "found an unexpected number of update sites: {0}", sites);
        return;
    }
    UpdateCenterMetadata ucm;
    try {
        ucm = ucmd.get(jenkins);
    } catch (IOException x) {
        LOGGER.log(Level.WARNING, "cannot load data for mock update center", x);
        return;
    }
    JSONObject all;
    try {
        all = new JSONObject(ucm.originalJSON);
        all.remove("signature");
        JSONObject plugins = all.getJSONObject("plugins");
        LOGGER.info(() -> "editing JSON with " + plugins.length() + " plugins to reflect " + ucm.plugins.size()
                + " possible overrides");
        for (PluginMetadata meta : ucm.plugins.values()) {
            String name = meta.getName();
            String version = meta.getVersion();
            JSONObject plugin = plugins.optJSONObject(name);
            if (plugin == null) {
                LOGGER.log(Level.INFO, "adding plugin {0}", name);
                plugin = new JSONObject().accumulate("name", name);
                plugins.put(name, plugin);
            }
            plugin.put("url", name + ".hpi");
            updating(plugin, "version", version);
            updating(plugin, "gav", meta.gav);
            updating(plugin, "requiredCore", meta.requiredCore().toString());
            updating(plugin, "dependencies", new JSONArray(meta.getDependencies().stream().map(d -> {
                try {
                    return new JSONObject().accumulate("name", d.name).accumulate("version", d.version)
                            .accumulate("optional", d.optional);
                } catch (JSONException x) {
                    throw new AssertionError(x);
                }
            }).collect(Collectors.toList())));
            plugin.remove("sha1");
        }
    } catch (JSONException x) {
        LOGGER.log(Level.WARNING, "cannot prepare mock update center", x);
        return;
    }
    HttpProcessor proc = HttpProcessorBuilder.create().add(new ResponseServer("MockUpdateCenter"))
            .add(new ResponseContent()).add(new RequestConnControl()).build();
    UriHttpRequestHandlerMapper handlerMapper = new UriHttpRequestHandlerMapper();
    String json = "updateCenter.post(\n" + all + "\n);";
    handlerMapper.register("/update-center.json",
            (HttpRequest request, HttpResponse response, HttpContext context) -> {
                response.setStatusCode(HttpStatus.SC_OK);
                response.setEntity(new StringEntity(json, ContentType.APPLICATION_JSON));
            });
    handlerMapper.register("*.hpi", (HttpRequest request, HttpResponse response, HttpContext context) -> {
        String plugin = request.getRequestLine().getUri().replaceFirst("^/(.+)[.]hpi$", "$1");
        PluginMetadata meta = ucm.plugins.get(plugin);
        if (meta == null) {
            LOGGER.log(Level.WARNING, "no such plugin {0}", plugin);
            response.setStatusCode(HttpStatus.SC_NOT_FOUND);
            return;
        }
        File local = meta.resolve(injector, meta.getVersion());
        LOGGER.log(Level.INFO, "serving {0}", local);
        response.setStatusCode(HttpStatus.SC_OK);
        response.setEntity(new FileEntity(local));
    });
    handlerMapper.register("*", (HttpRequest request, HttpResponse response, HttpContext context) -> {
        String location = original.replace("/update-center.json", request.getRequestLine().getUri());
        LOGGER.log(Level.INFO, "redirect to {0}", location);
        /* TODO for some reason DownloadService.loadJSONHTML does not seem to process the redirect, despite calling setInstanceFollowRedirects(true):
        response.setStatusCode(HttpStatus.SC_MOVED_TEMPORARILY);
        response.setHeader("Location", location);
         */
        HttpURLConnection uc = (HttpURLConnection) new URL(location).openConnection();
        uc.setInstanceFollowRedirects(true);
        // TODO consider caching these downloads locally like CachedUpdateCenterMetadataLoader does for the main update-center.json
        byte[] data = IOUtils.toByteArray(uc);
        String contentType = uc.getContentType();
        response.setStatusCode(HttpStatus.SC_OK);
        response.setEntity(new ByteArrayEntity(data, ContentType.create(contentType)));

    });
    server = ServerBootstrap.bootstrap().
    // could setLocalAddress if using a JenkinsController that requires it
            setHttpProcessor(proc).setHandlerMapper(handlerMapper).setExceptionLogger(serverExceptionHandler())
            .create();

    try {
        server.start();
    } catch (IOException x) {
        LOGGER.log(Level.WARNING, "cannot start mock update center", x);
        return;

    }
    original = sites.get(0);
    // TODO figure out how to deal with Docker-based controllers which would need to have an IP address for the host
    String override = "http://" + server.getInetAddress().getHostAddress() + ":" + server.getLocalPort()
            + "/update-center.json";
    LOGGER.log(Level.INFO, "replacing update site {0} with {1}", new Object[] { original, override });
    jenkins.runScript(
            "DownloadService.signatureCheck = false; Jenkins.instance.updateCenter.sites.replaceBy([new UpdateSite(UpdateCenter.ID_DEFAULT, '%s')])",
            override);
}

From source file:nl.knaw.dans.easy.sword2examples.Common.java

public static CloseableHttpResponse sendChunk(DigestInputStream dis, int size, String method, URI uri,
        String filename, String mimeType, CloseableHttpClient http, boolean inProgress) throws Exception {
    // System.out.println(String.format("Sending chunk to %s, filename = %s, chunk size = %d, MIME-Type = %s, In-Progress = %s ... ", uri.toString(),
    // filename, size, mimeType, Boolean.toString(inProgress)));
    byte[] chunk = readChunk(dis, size);
    String md5 = new String(Hex.encodeHex(dis.getMessageDigest().digest()));
    HttpUriRequest request = RequestBuilder.create(method).setUri(uri).setConfig(RequestConfig.custom()
            /*//from  w w  w.j a va  2s.co m
             * When using an HTTPS-connection EXPECT-CONTINUE must be enabled, otherwise buffer overflow may follow
             */
            .setExpectContinueEnabled(true).build()) //
            .addHeader("Content-Disposition", String.format("attachment; filename=%s", filename)) //
            .addHeader("Content-MD5", md5) //
            .addHeader("Packaging", BAGIT_URI) //
            .addHeader("In-Progress", Boolean.toString(inProgress)) //
            .setEntity(new ByteArrayEntity(chunk, ContentType.create(mimeType))) //
            .build();
    CloseableHttpResponse response = http.execute(request);
    // System.out.println("Response received.");
    return response;
}

From source file:tech.sirwellington.alchemy.http.HttpVerbImplTest.java

@Test
public void testExecuteWhenContentTypeInvalid() throws IOException {
    List<ContentType> invalidContentTypes = Arrays.asList(ContentType.APPLICATION_ATOM_XML,
            ContentType.TEXT_HTML, ContentType.TEXT_XML, ContentType.APPLICATION_XML,
            ContentType.APPLICATION_OCTET_STREAM, ContentType.create(one(alphabeticString())));

    ContentType invalidContentType = Lists.oneOf(invalidContentTypes);

    String string = one(alphanumericString());
    entity = new StringEntity(string, invalidContentType);

    when(apacheResponse.getEntity()).thenReturn(entity);

    HttpResponse result = instance.execute(apacheClient, request);
    assertThat(result.bodyAsString(), is(string));
    verify(apacheResponse).close();//from www .j  ava2s  . c o  m
}

From source file:com.intuit.karate.http.apache.ApacheHttpClient.java

@Override
protected HttpEntity getEntity(List<MultiPartItem> items, String mediaType) {
    boolean hasNullName = false;
    for (MultiPartItem item : items) {
        if (item.getName() == null) {
            hasNullName = true;//from   www  .j  ava2  s  . c  o m
            break;
        }
    }
    if (hasNullName) { // multipart/related
        String boundary = createBoundary();
        String text = getAsStringEntity(items, boundary);
        ContentType ct = ContentType.create(mediaType)
                .withParameters(new BasicNameValuePair("boundary", boundary));
        return new StringEntity(text, ct);
    } else {
        MultipartEntityBuilder builder = MultipartEntityBuilder.create()
                .setContentType(ContentType.create(mediaType));
        for (MultiPartItem item : items) {
            if (item.getValue() == null || item.getValue().isNull()) {
                logger.warn("ignoring null multipart value for key: {}", item.getName());
                continue;
            }
            String name = item.getName();
            ScriptValue sv = item.getValue();
            if (name == null) {
                // builder.addPart(bodyPart);
            } else {
                FormBodyPartBuilder formBuilder = FormBodyPartBuilder.create().setName(name);
                ContentBody contentBody;
                switch (sv.getType()) {
                case INPUT_STREAM:
                    InputStream is = (InputStream) sv.getValue();
                    contentBody = new InputStreamBody(is, ContentType.APPLICATION_OCTET_STREAM, name);
                    break;
                case XML:
                    contentBody = new StringBody(sv.getAsString(), ContentType.APPLICATION_XML);
                    break;
                case JSON:
                    contentBody = new StringBody(sv.getAsString(), ContentType.APPLICATION_JSON);
                    break;
                default:
                    contentBody = new StringBody(sv.getAsString(), ContentType.TEXT_PLAIN);
                }
                formBuilder = formBuilder.setBody(contentBody);
                builder = builder.addPart(formBuilder.build());
            }
        }
        return builder.build();
    }
}