Example usage for org.apache.http.client.methods HttpPost getMethod

List of usage examples for org.apache.http.client.methods HttpPost getMethod

Introduction

In this page you can find the example usage for org.apache.http.client.methods HttpPost getMethod.

Prototype

@Override
    public String getMethod() 

Source Link

Usage

From source file:org.openjena.riot.web.HttpOp.java

/** POST with response body.
 * <p>The content for the POST body comes from the HttpEntity.
 * <p>The response is handled bythe handler map, as per {@link #execHttpGet(String, String, Map)}
 *///from  w  ww . j a  va 2 s .c  o m
public static void execHttpPost(String url, HttpEntity provider, String acceptType,
        Map<String, HttpResponseHandler> handlers) {
    try {
        long id = counter.incrementAndGet();
        String requestURI = determineBaseIRI(url);
        String baseIRI = determineBaseIRI(requestURI);

        HttpPost httppost = new HttpPost(requestURI);
        if (log.isDebugEnabled())
            log.debug(format("[%d] %s %s", id, httppost.getMethod(), httppost.getURI().toString()));

        if (provider.getContentType() == null)
            log.debug(format("[%d] No content type"));

        // Execute
        HttpClient httpclient = new DefaultHttpClient();
        httppost.setEntity(provider);
        HttpResponse response = httpclient.execute(httppost);
        httpResponse(id, response, baseIRI, handlers);

        httpclient.getConnectionManager().shutdown();
    } catch (IOException ex) {
        ex.printStackTrace(System.err);
    } finally {
        closeEntity(provider);
    }
}

From source file:nl.nn.adapterframework.http.HttpResponseMock.java

public InputStream doPost(HttpHost host, HttpPost request, HttpContext context) throws IOException {
    assertEquals("POST", request.getMethod());
    StringBuilder response = new StringBuilder();
    String lineSeparator = System.getProperty("line.separator");
    response.append(request.toString() + lineSeparator);

    Header[] headers = request.getAllHeaders();
    for (Header header : headers) {
        response.append(header.getName() + ": " + header.getValue() + lineSeparator);
    }/*w  w  w  . j  a v  a2  s.  com*/
    HttpEntity entity = request.getEntity();
    if (entity instanceof MultipartEntity) {
        MultipartEntity multipartEntity = (MultipartEntity) entity;
        ByteArrayOutputStream baos = new ByteArrayOutputStream();
        multipartEntity.writeTo(baos);
        String contentType = multipartEntity.getContentType().getValue();
        String boundary = getBoundary(contentType);
        contentType = contentType.replaceAll(boundary, "IGNORE");
        response.append("Content-Type: " + contentType + lineSeparator);

        response.append(lineSeparator);
        String content = new String(baos.toByteArray());
        content = content.replaceAll(boundary, "IGNORE");
        response.append(content);
    } else {
        response.append(lineSeparator);
        response.append(EntityUtils.toString(entity));
    }

    return new ByteArrayInputStream(response.toString().getBytes());
}

From source file:com.threatconnect.sdk.conn.HttpRequestExecutor.java

@Override
public String executeUploadByteStream(String path, File file) throws IOException {
    if (this.conn.getConfig() == null) {
        throw new IllegalStateException("Can't execute HTTP request when configuration is undefined.");
    }//from ww w.  jav  a2 s.c  o m

    String fullPath = this.conn.getConfig().getTcApiUrl() + path.replace("/api/", "/");

    logger.trace("Calling POST: " + fullPath);
    HttpPost httpBase = new HttpPost(fullPath);
    httpBase.setEntity(new FileEntity(file));
    String headerPath = httpBase.getURI().getRawPath() + "?" + httpBase.getURI().getRawQuery();
    ConnectionUtil.applyHeaders(this.conn.getConfig(), httpBase, httpBase.getMethod(), headerPath,
            ContentType.APPLICATION_OCTET_STREAM.toString());

    logger.trace("Request: " + httpBase.getRequestLine());

    CloseableHttpResponse response = this.conn.getApiClient().execute(httpBase);
    String result = null;

    logger.trace(response.getStatusLine().toString());
    HttpEntity entity = response.getEntity();
    if (entity != null) {
        try {
            result = EntityUtils.toString(entity, "iso-8859-1");
            logger.trace("Result:" + result);
            EntityUtils.consume(entity);
        } finally {
            response.close();
        }

    }

    return result;
}

From source file:com.ibm.sbt.security.authentication.oauth.consumer.HMACOAuth1Handler.java

@Override
public void getRequestTokenFromServer() throws OAuthException {

    int responseCode = HttpStatus.SC_OK;
    Context context = Context.get();
    String responseBody = "";
    try {/*w  w w .ja  va  2 s  .  co m*/
        HttpClient client = new DefaultHttpClient();
        if (getForceTrustSSLCertificate()) {
            client = SSLUtil.wrapHttpClient((DefaultHttpClient) client);
        }

        // In case of Twitter, this callback URL registered can be different from the URL specified below.
        String callbackUrl = getCallbackUrl(context);
        String consumerKey = getConsumerKey();
        String nonce = getNonce();
        String timeStamp = getTimestamp();

        // HMAC requires parameter to be alphabetically sorted, using LinkedHashMap below to preserve
        // ordering
        LinkedHashMap<String, String> signatureParamsMap = new LinkedHashMap<String, String>();
        signatureParamsMap.put(Configuration.CALLBACK, callbackUrl);
        signatureParamsMap.put(Configuration.CONSUMER_KEY, consumerKey);
        signatureParamsMap.put(Configuration.NONCE, nonce);
        signatureParamsMap.put(Configuration.SIGNATURE_METHOD, getSignatureMethod());
        signatureParamsMap.put(Configuration.TIMESTAMP, timeStamp);
        signatureParamsMap.put(Configuration.VERSION, Configuration.OAUTH_VERSION1);

        String consumerSecret = getConsumerSecret();
        String requestPostUrl = getRequestTokenURL();
        HttpPost method = new HttpPost(requestPostUrl);
        String signature = HMACEncryptionUtility.generateHMACSignature(requestPostUrl, method.getMethod(),
                consumerSecret, "", signatureParamsMap);

        StringBuilder headerStr = new StringBuilder();
        headerStr.append("OAuth ").append(Configuration.CALLBACK).append("=\"").append(callbackUrl)
                .append("\"");
        headerStr.append(",").append(Configuration.CONSUMER_KEY).append("=\"").append(consumerKey).append("\"");
        headerStr.append(",").append(Configuration.SIGNATURE_METHOD).append("=\"").append(getSignatureMethod())
                .append("\"");
        headerStr.append(",").append(Configuration.TIMESTAMP).append("=\"").append(timeStamp).append("\"");
        headerStr.append(",").append(Configuration.NONCE).append("=\"").append(nonce).append("\"");
        headerStr.append(",").append(Configuration.VERSION).append("=\"").append(Configuration.OAUTH_VERSION1)
                .append("\"");
        headerStr.append(",").append(Configuration.SIGNATURE).append("=\"")
                .append(URLEncoder.encode(signature, "UTF-8")).append("\"");
        method.setHeader("Authorization", headerStr.toString());

        HttpResponse httpResponse = client.execute(method);
        responseCode = httpResponse.getStatusLine().getStatusCode();
        InputStream content = httpResponse.getEntity().getContent();
        BufferedReader reader = new BufferedReader(new InputStreamReader(content));
        try {
            responseBody = StreamUtil.readString(reader);
        } finally {
            StreamUtil.close(reader);
        }

    } catch (Exception e) {
        throw new OAuthException(e, "Internal error - getRequestToken failed Exception: ");
    }
    if (responseCode != HttpStatus.SC_OK) {
        String exceptionDetail = buildErrorMessage(responseCode, responseBody);
        if (StringUtil.isNotEmpty(exceptionDetail)) {
            throw new OAuthException(null,
                    "HMACOAuth1Handler.java : getRequestTokenFromServer failed." + exceptionDetail);
        }
    } else {
        /*
         * The Response from Twitter contains OAuth request token, OAuth request token secret, and a
         * boolean oauth_callback_confirmed with value set as true or false.
         */
        setRequestToken(getTokenValue(responseBody, Configuration.OAUTH_TOKEN));
        setRequestTokenSecret(getTokenValue(responseBody, Configuration.OAUTH_TOKEN_SECRET));
        /*
         * OAUTH_CALLBACK_CONFIRMED : This property can be used for debugging applications which have not
         * provided the Callback URL while registering the Application. If OAUTH_CALLBACK_CONFIRMED is
         * returned as false, then the application needs to be modified to set a callback url. However,
         * when the Application has specified the Callback Url, and is different from the callback Url we
         * are passing, this property value is returned as true.
         */
        setOAuthCallbackConfirmed(getTokenValue(responseBody, Configuration.OAUTH_CALLBACK_CONFIRMED));
    }

}

From source file:com.hzq.car.CarTest.java

/**
 * ??post,json/* w  w  w.j  a va  2s  .c  om*/
 */
private String sendAndGetResponse(String url, List<NameValuePair> params) throws IOException {
    HttpPost post = new HttpPost(url);
    post.setEntity(new UrlEncodedFormEntity(params, "UTF-8"));
    StringBuilder messageBuilder = new StringBuilder("\n");
    messageBuilder.append(post.getMethod());
    messageBuilder.append("  ");
    messageBuilder.append(post.getURI());
    messageBuilder.append("  ");
    HttpEntity entity = post.getEntity();
    String body = IOUtils.toString(entity.getContent());
    List<NameValuePair> parse = URLEncodedUtils.parse(body, ContentType.get(entity).getCharset());
    parse.stream().forEach(pair -> {
        messageBuilder.append(pair.getName());
        messageBuilder.append(":");
        messageBuilder.append(pair.getValue());
        messageBuilder.append(" ");
    });
    logger.warn("send httpRequest: {}", messageBuilder.toString());
    CloseableHttpResponse response = client.execute(post);
    InputStream content = response.getEntity().getContent();
    String s = IOUtils.toString(content);
    response.close();
    logger.warn("get httpResponse: \n{}", s);
    return s;
}

From source file:de.unioninvestment.eai.portal.portlet.crud.scripting.domain.container.rest.ReSTDelegateImpl.java

private void sendPostRequest(GenericItem item, ReSTChangeConfig changeConfig)
        throws IOException, ClientProtocolException {

    byte[] content = creator.create(item, changeConfig.getValue(), config.getCharset());
    URI uri = createURI(item, changeConfig.getUrl());
    HttpPost request = new HttpPost(uri);
    ContentType contentType = createContentType();
    request.setEntity(new ByteArrayEntity(content, contentType));

    try {//from  ww w. j  a  v a  2  s  .co m
        HttpResponse response = httpClient.execute(request);

        auditLogger.auditReSTRequest(request.getMethod(), uri.toString(),
                new String(content, config.getCharset()), response.getStatusLine().toString());

        expectAnyStatusCode(response, HttpStatus.SC_CREATED, HttpStatus.SC_NO_CONTENT);

    } finally {
        request.releaseConnection();
    }
}

From source file:org.sahli.asciidoc.confluence.publisher.client.http.HttpRequestFactoryTest.java

@Test
public void addAttachmentRequest_withValidParameters_returnsValidHttpPostWithMultipartEntity()
        throws Exception {
    // arrange//from www .j  a va2s . co  m
    String contentId = "1234";
    String attachmentFileName = "attachment.txt";
    InputStream attachmentContent = new ByteArrayInputStream("Some text".getBytes());

    // act
    HttpPost addAttachmentRequest = this.httpRequestFactory.addAttachmentRequest(contentId, attachmentFileName,
            attachmentContent);

    // assert
    assertThat(addAttachmentRequest.getMethod(), is("POST"));
    assertThat(addAttachmentRequest.getURI().toString(),
            is(CONFLUENCE_REST_API_ENDPOINT + "/content/" + contentId + "/child/attachment"));
    assertThat(addAttachmentRequest.getFirstHeader("X-Atlassian-Token").getValue(), is("no-check"));

    ByteArrayOutputStream entityContent = new ByteArrayOutputStream();
    addAttachmentRequest.getEntity().writeTo(entityContent);
    String multiPartPayload = entityContent.toString("UTF-8");
    assertThat(multiPartPayload, containsString("attachment.txt"));
    assertThat(multiPartPayload, containsString("Some text"));
}

From source file:org.sahli.asciidoc.confluence.publisher.client.http.HttpRequestFactoryTest.java

@Test
public void addPageUnderAncestorRequest_withAncestorId_returnsValidHttpPostWithAncestorIdWithoutSpaceKey()
        throws Exception {
    // arrange/*w  w w. j a  v a2  s  .  c  o  m*/
    String spaceKey = "~personalSpace";
    String ancestorId = "1234";
    String title = "title";
    String content = "content";

    // act
    HttpPost addPageUnderAncestorRequest = this.httpRequestFactory.addPageUnderAncestorRequest(spaceKey,
            ancestorId, title, content);

    // assert
    assertThat(addPageUnderAncestorRequest.getMethod(), is("POST"));
    assertThat(addPageUnderAncestorRequest.getURI().toString(), is(CONFLUENCE_REST_API_ENDPOINT + "/content"));
    assertThat(addPageUnderAncestorRequest.getFirstHeader("Content-Type").getValue(),
            is(APPLICATION_JSON_UTF8));

    String jsonPayload = inputStreamAsString(addPageUnderAncestorRequest.getEntity().getContent());
    String expectedJsonPayload = fileContent(
            Paths.get(CLASS_LOCATION, "add-page-request-ancestor-id.json").toString());
    assertThat(jsonPayload, SameJsonAsMatcher.isSameJsonAs(expectedJsonPayload));
}

From source file:org.sahli.asciidoc.confluence.publisher.client.http.HttpRequestFactoryTest.java

@Test
public void updateAttachmentContentRequest_withValidParameters_returnsHttpPutRequestWithMultipartEntity()
        throws Exception {
    // arrange/* w  ww. j a  va  2 s  .c o  m*/
    String contentId = "1234";
    String attachmentId = "45";
    InputStream attachmentContent = new ByteArrayInputStream("hello".getBytes());

    // act
    HttpPost updateAttachmentContentRequest = this.httpRequestFactory.updateAttachmentContentRequest(contentId,
            attachmentId, attachmentContent);

    // assert
    assertThat(updateAttachmentContentRequest.getMethod(), is("POST"));
    assertThat(updateAttachmentContentRequest.getURI().toString(), is(CONFLUENCE_REST_API_ENDPOINT + "/content/"
            + contentId + "/child/attachment/" + attachmentId + "/data"));
    assertThat(updateAttachmentContentRequest.getFirstHeader("X-Atlassian-Token").getValue(), is("no-check"));

    ByteArrayOutputStream entityContent = new ByteArrayOutputStream();
    updateAttachmentContentRequest.getEntity().writeTo(entityContent);
    String multiPartPayload = entityContent.toString("UTF-8");
    assertThat(multiPartPayload, containsString("hello"));
}

From source file:jsonbroker.library.client.http.HttpDispatcher.java

private HttpRequestBase buildPostRequest(HttpRequestAdapter requestAdapter, Authenticator authenticator) {

    String requestUri = requestAdapter.getRequestUri();
    Entity entity = requestAdapter.getRequestEntity();

    String host = _networkAddress.getHostAddress();
    int port = _networkAddress.getPort();

    String uri = String.format("http://%s:%d%s", host, port, requestUri);
    //       log.debug( uri, "uri" );

    HttpPost answer = new HttpPost(uri);

    // extra headers ... 
    {/*  ww  w.j a v  a  2 s .c  om*/
        HashMap<String, String> requestHeaders = requestAdapter.getRequestHeaders();
        for (Map.Entry<String, String> item : requestHeaders.entrySet()) {
            answer.setHeader(item.getKey(), item.getValue());
        }
    }

    // auth headers ... 
    if (null != authenticator) {
        String authorization = authenticator.getRequestAuthorization(answer.getMethod(), requestUri, entity);
        log.debug(authorization, "authorization");
        if (null != authorization) {
            answer.addHeader("Authorization", authorization);
        }
    }

    InputStreamEntity inputStreamEntity = new InputStreamEntity(entity.getContent(), entity.getContentLength());
    answer.setEntity(inputStreamEntity);

    return answer;

}