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

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

Introduction

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

Prototype

String METHOD_NAME

To view the source code for org.apache.http.client.methods HttpPost METHOD_NAME.

Click Source Link

Usage

From source file:ch.cyberduck.core.dropbox.client.DropboxClient.java

/**
 * Delete a file.// w  ww. j  a  v  a 2  s . co m
 */
public void delete(String path) throws IOException {

    String[] params = { "root", ROOT, "path", path };
    HttpResponse response = request(this.buildRequest(HttpPost.METHOD_NAME, "/fileops/delete", params));
    this.finish(response);
}

From source file:com.manning.androidhacks.hack023.net.FollowPostRedirectHandler.java

/**
 * HttpClient is compliant with the requirements of the HTTP specification
 * (RFC 2616) and does not automatically redirect other methods than GET and
 * HEAD. We have to override this method to automatically follow redirects
 * when using the POST method.//from  w  w w.  ja  va2s  . com
 */
@Override
public boolean isRedirectRequested(final HttpResponse response, final HttpContext context) {
    if (response == null) {
        throw new IllegalArgumentException("HTTP response may not be null");
    }

    int statusCode = response.getStatusLine().getStatusCode();
    switch (statusCode) {
    case HttpStatus.SC_MOVED_TEMPORARILY:
    case HttpStatus.SC_MOVED_PERMANENTLY:
    case HttpStatus.SC_TEMPORARY_REDIRECT:
        HttpRequest request = (HttpRequest) context.getAttribute(ExecutionContext.HTTP_REQUEST);
        String method = request.getRequestLine().getMethod();
        return method.equalsIgnoreCase(HttpGet.METHOD_NAME) || method.equalsIgnoreCase(HttpHead.METHOD_NAME)
                || method.equalsIgnoreCase(HttpPost.METHOD_NAME);
    case HttpStatus.SC_SEE_OTHER:
        return true;
    default:
        return false;
    }
}

From source file:org.elasticsearch.test.rest.spec.RestApi.java

/**
 * Returns the supported http methods given the rest parameters provided
 *///from   ww w . java2 s. c  om
public List<String> getSupportedMethods(Set<String> restParams) {
    //we try to avoid hardcoded mappings but the index api is the exception
    if ("index".equals(name) || "create".equals(name)) {
        List<String> indexMethods = Lists.newArrayList();
        for (String method : methods) {
            if (restParams.contains("id")) {
                //PUT when the id is provided
                if (HttpPut.METHOD_NAME.equals(method)) {
                    indexMethods.add(method);
                }
            } else {
                //POST without id
                if (HttpPost.METHOD_NAME.equals(method)) {
                    indexMethods.add(method);
                }
            }
        }
        return indexMethods;
    }

    return methods;
}

From source file:com.trickl.crawler.protocol.http.HttpProtocol.java

@Override
public ManagedContentEntity load(URI uri) throws IOException {
    HttpRequestBase httpRequest;/*from   w  ww.  j  av a  2 s.c  om*/

    if (method.equalsIgnoreCase(HttpPost.METHOD_NAME)) {
        HttpPost httpPost = new HttpPost(uri);

        // Add header data
        for (Map.Entry<String, String> headerDataEntry : headerData.entrySet()) {
            httpPost.setHeader(headerDataEntry.getKey(), headerDataEntry.getValue());
        }

        // Add post data
        String contentType = headerData.get("Content-Type");
        if (contentType == null || "application/x-www-form-urlencoded".equalsIgnoreCase(contentType)) {
            List<NameValuePair> nameValuePairs = new ArrayList<NameValuePair>();
            for (Map.Entry<String, Object> postDataEntry : postData.entrySet()) {
                nameValuePairs.add(
                        new BasicNameValuePair(postDataEntry.getKey(), postDataEntry.getValue().toString()));
            }
            httpPost.setEntity(new UrlEncodedFormEntity(nameValuePairs));
        } else if ("application/json".equalsIgnoreCase(contentType)) {
            ObjectMapper mapper = new ObjectMapper();
            StringEntity se;
            try {
                String jsonString = mapper.writeValueAsString(postData);
                se = new StringEntity(jsonString);
                httpPost.setEntity(se);
            } catch (JsonGenerationException ex) {
                log.error("Failed to generate JSON.", ex);
            } catch (JsonMappingException ex) {
                log.error("Failed to generate JSON.", ex);
            }
        }
        httpRequest = httpPost;
    } else {
        httpRequest = new HttpGet(uri);
    }

    HttpResponse response = httpclient.execute(httpRequest);
    StatusLine statusline = response.getStatusLine();
    if (statusline.getStatusCode() >= HttpStatus.SC_BAD_REQUEST) {
        httpRequest.abort();
        throw new HttpResponseException(statusline.getStatusCode(), statusline.getReasonPhrase());
    }
    HttpEntity entity = response.getEntity();
    if (entity == null) {
        // Should _almost_ never happen with HTTP GET requests.
        throw new ClientProtocolException("Empty entity");
    }
    long maxlen = httpclient.getParams().getLongParameter(DroidsHttpClient.MAX_BODY_LENGTH, 0);
    return new HttpContentEntity(entity, maxlen);
}

From source file:org.apache.brooklyn.entity.brooklynnode.CallbackEntityHttpClient.java

@Override
public HttpToolResponse post(String path, Map<String, String> headers, Map<String, String> formParams) {
    String result = callback.apply(new Request(entity, HttpPost.METHOD_NAME, path, formParams));
    return new HttpToolResponse(HttpStatus.SC_OK, Collections.<String, List<String>>emptyMap(),
            result.getBytes(), 0, 0, 0);
}

From source file:io.wcm.caravan.io.http.impl.RequestUtilTest.java

@Test
public void testBuildHttpRequest_Post() throws ParseException, IOException {
    RequestTemplate template = new RequestTemplate().method("post").append("/path").body("string body");
    HttpUriRequest request = RequestUtil.buildHttpRequest("http://host", template.request());

    assertEquals("http://host/path", request.getURI().toString());
    assertEquals(HttpPost.METHOD_NAME, request.getMethod());

    HttpEntityEnclosingRequest entityRequest = (HttpEntityEnclosingRequest) request;
    assertEquals("string body", EntityUtils.toString(entityRequest.getEntity()));
}

From source file:me.ixfan.wechatkit.util.HttpClientUtil.java

/**
 * Send HTTP request with specified HTTP method.
 * If method is not specified, GET method will be used.
 * @param url URL of request.//from www.java  2 s  .c  o m
 * @param method HTTP method used.
 * @param nameValuePairs name/stringValue pairs parameter used as an element of HTTP messages.
 * @return JSON object of response.
 * @throws IOException If I/O error occurs.
 */
private static JsonObject sendRequestAndGetJsonResponse(String url, String method,
        NameValuePair... nameValuePairs) throws IOException {
    CloseableHttpClient httpClient = HttpClients.createDefault();

    HttpUriRequest request;
    switch (method) {
    case HttpPost.METHOD_NAME:
        request = RequestBuilder.post(url).setCharset(Charsets.UTF_8)
                .setEntity(new UrlEncodedFormEntity(Arrays.asList(nameValuePairs))).build();
        break;
    default:
        request = RequestBuilder.get(url).setCharset(Charsets.UTF_8).build();
        break;
    }

    return httpClient.execute(request, new JsonResponseHandler());
}

From source file:ch.cyberduck.core.dropbox.client.DropboxClient.java

/**
 * Move a file.//from   ww  w.j  av a2s  .c  o  m
 */
public void move(String from_path, String to_path) throws IOException {
    String[] params = { "root", ROOT, "from_path", from_path, "to_path", to_path };

    HttpResponse response = request(this.buildRequest(HttpPost.METHOD_NAME, "/fileops/move", params));
    this.finish(response);
}

From source file:com.wudaosoft.net.httpclient.SortHeadersInterceptor.java

@Override
public void process(HttpRequest request, HttpContext context) throws HttpException, IOException {
    if (!request.containsHeader("Accept")) {
        request.addHeader("Accept",
                "text/html,application/xhtml+xml,application/xml;q=0.9,image/webp,*/*;q=0.8");
    }//  www.j  a v  a2 s .  com

    if (!request.containsHeader("Content-Type")) {
        request.addHeader("Content-Type", "application/x-www-form-urlencoded;charset=UTF-8");
    }

    //      request.addHeader("Accept-Language", "zh-CN,zh;q=0.8,ja;q=0.6,en;q=0.4");
    request.addHeader("Cache-Control", "no-cache");
    request.addHeader("Pragma", "no-cache");

    if (request.containsHeader("X-Requested-With")) {

        String method = ((HttpUriRequest) request).getMethod();

        if (HttpPost.METHOD_NAME.equals(method) || HttpPut.METHOD_NAME.equals(method)
                || HttpPatch.METHOD_NAME.equals(method)) {
            //            request.setHeader("Accept", "application/json, text/javascript, */*; q=0.01");
            request.setHeader("Content-Type", "application/x-www-form-urlencoded; charset=UTF-8");
        }

        request.addHeader("Origin", hostConfig.getHostUrl());
    }

    if (!request.containsHeader("Referer") && hostConfig.getReferer() != null) {
        request.addHeader("Referer", hostConfig.getReferer());
    }

    request.setHeader("User-Agent", hostConfig.getUserAgent() != null ? hostConfig.getUserAgent() : userAgent);

    copyAndSet(sortKeyList, request);
}