Search in sources :

Example 31 with HttpEntityEnclosingRequestBase

use of org.apache.http.client.methods.HttpEntityEnclosingRequestBase in project afinal by yangfuhai.

the class FinalHttp method post.

public void post(String url, Header[] headers, HttpEntity entity, String contentType, AjaxCallBack<? extends Object> callBack) {
    HttpEntityEnclosingRequestBase request = addEntityToRequestBase(new HttpPost(url), entity);
    if (headers != null)
        request.setHeaders(headers);
    sendRequest(httpClient, httpContext, request, contentType, callBack);
}
Also used : HttpPost(org.apache.http.client.methods.HttpPost) HttpEntityEnclosingRequestBase(org.apache.http.client.methods.HttpEntityEnclosingRequestBase)

Example 32 with HttpEntityEnclosingRequestBase

use of org.apache.http.client.methods.HttpEntityEnclosingRequestBase in project ThinkAndroid by white-cat.

the class AsyncHttpClient method post.

/**
	 * Perform a HTTP POST request and track the Android Context which initiated
	 * the request. Set headers only for this request
	 * 
	 * @param context
	 *            the Android Context which initiated the request.
	 * @param url
	 *            the URL to send the request to.
	 * @param headers
	 *            set headers only for this request
	 * @param entity
	 *            a raw {@link HttpEntity} to send with the request, for
	 *            example, use this to send string/json/xml payloads to a server
	 *            by passing a {@link org.apache.http.entity.StringEntity}.
	 * @param contentType
	 *            the content type of the payload you are sending, for example
	 *            application/json if sending a json payload.
	 * @param responseHandler
	 *            the response handler instance that should handle the response.
	 */
public void post(Context context, String url, Header[] headers, HttpEntity entity, String contentType, AsyncHttpResponseHandler responseHandler) {
    HttpEntityEnclosingRequestBase request = addEntityToRequestBase(new HttpPost(url), entity);
    if (headers != null)
        request.setHeaders(headers);
    sendRequest(httpClient, httpContext, request, contentType, responseHandler, context);
}
Also used : HttpPost(org.apache.http.client.methods.HttpPost) HttpEntityEnclosingRequestBase(org.apache.http.client.methods.HttpEntityEnclosingRequestBase)

Example 33 with HttpEntityEnclosingRequestBase

use of org.apache.http.client.methods.HttpEntityEnclosingRequestBase in project Activiti by Activiti.

the class TaskVariablesCollectionResourceTest method doSingleTaskVariableTest.

private void doSingleTaskVariableTest(String httpMethod) throws Exception {
    ProcessInstance processInstance = runtimeService.startProcessInstanceByKey("oneTaskProcess");
    Task task = taskService.createTaskQuery().processInstanceId(processInstance.getId()).singleResult();
    ArrayNode requestNode = objectMapper.createArrayNode();
    ObjectNode variableNode = requestNode.addObject();
    variableNode.put("name", "myVariable");
    variableNode.put("value", "simple string value");
    variableNode.put("scope", "local");
    variableNode.put("type", "string");
    HttpEntityEnclosingRequestBase httpCall;
    // Create a new local variable
    if (httpMethod.equals("POST")) {
        httpCall = new HttpPost(SERVER_URL_PREFIX + RestUrls.createRelativeResourceUrl(RestUrls.URL_TASK_VARIABLES_COLLECTION, task.getId()));
    } else {
        httpCall = new HttpPut(SERVER_URL_PREFIX + RestUrls.createRelativeResourceUrl(RestUrls.URL_TASK_VARIABLES_COLLECTION, task.getId()));
    }
    httpCall.setEntity(new StringEntity(requestNode.toString()));
    CloseableHttpResponse response = executeRequest(httpCall, HttpStatus.SC_CREATED);
    JsonNode responseNode = objectMapper.readTree(response.getEntity().getContent()).get(0);
    closeResponse(response);
    assertNotNull(responseNode);
    assertEquals("myVariable", responseNode.get("name").asText());
    assertEquals("simple string value", responseNode.get("value").asText());
    assertEquals("local", responseNode.get("scope").asText());
    assertEquals("string", responseNode.get("type").asText());
    assertNull(responseNode.get("valueUrl"));
    assertTrue(taskService.hasVariableLocal(task.getId(), "myVariable"));
    assertEquals("simple string value", taskService.getVariableLocal(task.getId(), "myVariable"));
    // Create a new global variable
    variableNode.put("name", "myVariable");
    variableNode.put("value", "Another simple string value");
    variableNode.put("scope", "global");
    variableNode.put("type", "string");
    if (httpMethod.equals("POST")) {
        httpCall = new HttpPost(SERVER_URL_PREFIX + RestUrls.createRelativeResourceUrl(RestUrls.URL_TASK_VARIABLES_COLLECTION, task.getId()));
    } else {
        httpCall = new HttpPut(SERVER_URL_PREFIX + RestUrls.createRelativeResourceUrl(RestUrls.URL_TASK_VARIABLES_COLLECTION, task.getId()));
    }
    httpCall.setEntity(new StringEntity(requestNode.toString()));
    response = executeRequest(httpCall, HttpStatus.SC_CREATED);
    responseNode = objectMapper.readTree(response.getEntity().getContent()).get(0);
    closeResponse(response);
    assertNotNull(responseNode);
    assertEquals("myVariable", responseNode.get("name").asText());
    assertEquals("Another simple string value", responseNode.get("value").asText());
    assertEquals("global", responseNode.get("scope").asText());
    assertEquals("string", responseNode.get("type").asText());
    assertNull(responseNode.get("valueUrl"));
    assertTrue(runtimeService.hasVariable(task.getExecutionId(), "myVariable"));
    assertEquals("Another simple string value", runtimeService.getVariableLocal(task.getExecutionId(), "myVariable"));
    // Create a new scope-less variable, which defaults to local variables
    variableNode.removeAll();
    variableNode.put("name", "scopelessVariable");
    variableNode.put("value", "simple string value");
    variableNode.put("type", "string");
    if (httpMethod.equals("POST")) {
        httpCall = new HttpPost(SERVER_URL_PREFIX + RestUrls.createRelativeResourceUrl(RestUrls.URL_TASK_VARIABLES_COLLECTION, task.getId()));
    } else {
        httpCall = new HttpPut(SERVER_URL_PREFIX + RestUrls.createRelativeResourceUrl(RestUrls.URL_TASK_VARIABLES_COLLECTION, task.getId()));
    }
    httpCall.setEntity(new StringEntity(requestNode.toString()));
    response = executeRequest(httpCall, HttpStatus.SC_CREATED);
    responseNode = objectMapper.readTree(response.getEntity().getContent()).get(0);
    closeResponse(response);
    assertNotNull(responseNode);
    assertEquals("scopelessVariable", responseNode.get("name").asText());
    assertEquals("simple string value", responseNode.get("value").asText());
    assertEquals("local", responseNode.get("scope").asText());
    assertEquals("string", responseNode.get("type").asText());
    assertNull(responseNode.get("valueUrl"));
    assertTrue(taskService.hasVariableLocal(task.getId(), "scopelessVariable"));
    assertEquals("simple string value", taskService.getVariableLocal(task.getId(), "scopelessVariable"));
}
Also used : HttpPost(org.apache.http.client.methods.HttpPost) StringEntity(org.apache.http.entity.StringEntity) Task(org.activiti.engine.task.Task) HttpEntityEnclosingRequestBase(org.apache.http.client.methods.HttpEntityEnclosingRequestBase) ObjectNode(com.fasterxml.jackson.databind.node.ObjectNode) CloseableHttpResponse(org.apache.http.client.methods.CloseableHttpResponse) ProcessInstance(org.activiti.engine.runtime.ProcessInstance) JsonNode(com.fasterxml.jackson.databind.JsonNode) ArrayNode(com.fasterxml.jackson.databind.node.ArrayNode) HttpPut(org.apache.http.client.methods.HttpPut)

Example 34 with HttpEntityEnclosingRequestBase

use of org.apache.http.client.methods.HttpEntityEnclosingRequestBase in project camel by apache.

the class RestletPostContentTest method testPostBody.

@Test
public void testPostBody() throws Exception {
    HttpUriRequest method = new HttpPost("http://localhost:" + portNum + "/users/homer");
    ((HttpEntityEnclosingRequestBase) method).setEntity(new StringEntity(MSG_BODY));
    HttpResponse response = doExecute(method);
    assertHttpResponse(response, 200, "text/plain");
}
Also used : HttpUriRequest(org.apache.http.client.methods.HttpUriRequest) HttpPost(org.apache.http.client.methods.HttpPost) StringEntity(org.apache.http.entity.StringEntity) HttpEntityEnclosingRequestBase(org.apache.http.client.methods.HttpEntityEnclosingRequestBase) HttpResponse(org.apache.http.HttpResponse) Test(org.junit.Test)

Example 35 with HttpEntityEnclosingRequestBase

use of org.apache.http.client.methods.HttpEntityEnclosingRequestBase in project lucene-solr by apache.

the class HttpSolrClient method createMethod.

protected HttpRequestBase createMethod(final SolrRequest request, String collection) throws IOException, SolrServerException {
    SolrParams params = request.getParams();
    Collection<ContentStream> streams = requestWriter.getContentStreams(request);
    String path = requestWriter.getPath(request);
    if (path == null || !path.startsWith("/")) {
        path = DEFAULT_PATH;
    }
    ResponseParser parser = request.getResponseParser();
    if (parser == null) {
        parser = this.parser;
    }
    // The parser 'wt=' and 'version=' params are used instead of the original
    // params
    ModifiableSolrParams wparams = new ModifiableSolrParams(params);
    if (parser != null) {
        wparams.set(CommonParams.WT, parser.getWriterType());
        wparams.set(CommonParams.VERSION, parser.getVersion());
    }
    if (invariantParams != null) {
        wparams.add(invariantParams);
    }
    String basePath = baseUrl;
    if (collection != null)
        basePath += "/" + collection;
    if (request instanceof V2Request) {
        if (System.getProperty("solr.v2RealPath") == null) {
            basePath = baseUrl.replace("/solr", "/v2");
        } else {
            basePath = baseUrl + "/____v2";
        }
    }
    if (SolrRequest.METHOD.GET == request.getMethod()) {
        if (streams != null) {
            throw new SolrException(SolrException.ErrorCode.BAD_REQUEST, "GET can't send streams!");
        }
        return new HttpGet(basePath + path + wparams.toQueryString());
    }
    if (SolrRequest.METHOD.DELETE == request.getMethod()) {
        return new HttpDelete(basePath + path + wparams.toQueryString());
    }
    if (SolrRequest.METHOD.POST == request.getMethod() || SolrRequest.METHOD.PUT == request.getMethod()) {
        String url = basePath + path;
        boolean hasNullStreamName = false;
        if (streams != null) {
            for (ContentStream cs : streams) {
                if (cs.getName() == null) {
                    hasNullStreamName = true;
                    break;
                }
            }
        }
        boolean isMultipart = ((this.useMultiPartPost && SolrRequest.METHOD.POST == request.getMethod()) || (streams != null && streams.size() > 1)) && !hasNullStreamName;
        LinkedList<NameValuePair> postOrPutParams = new LinkedList<>();
        if (streams == null || isMultipart) {
            // send server list and request list as query string params
            ModifiableSolrParams queryParams = calculateQueryParams(this.queryParams, wparams);
            queryParams.add(calculateQueryParams(request.getQueryParams(), wparams));
            String fullQueryUrl = url + queryParams.toQueryString();
            HttpEntityEnclosingRequestBase postOrPut = SolrRequest.METHOD.POST == request.getMethod() ? new HttpPost(fullQueryUrl) : new HttpPut(fullQueryUrl);
            if (!isMultipart) {
                postOrPut.addHeader("Content-Type", "application/x-www-form-urlencoded; charset=UTF-8");
            }
            List<FormBodyPart> parts = new LinkedList<>();
            Iterator<String> iter = wparams.getParameterNamesIterator();
            while (iter.hasNext()) {
                String p = iter.next();
                String[] vals = wparams.getParams(p);
                if (vals != null) {
                    for (String v : vals) {
                        if (isMultipart) {
                            parts.add(new FormBodyPart(p, new StringBody(v, StandardCharsets.UTF_8)));
                        } else {
                            postOrPutParams.add(new BasicNameValuePair(p, v));
                        }
                    }
                }
            }
            // TODO: remove deprecated - first simple attempt failed, see {@link MultipartEntityBuilder}
            if (isMultipart && streams != null) {
                for (ContentStream content : streams) {
                    String contentType = content.getContentType();
                    if (contentType == null) {
                        // default
                        contentType = BinaryResponseParser.BINARY_CONTENT_TYPE;
                    }
                    String name = content.getName();
                    if (name == null) {
                        name = "";
                    }
                    parts.add(new FormBodyPart(name, new InputStreamBody(content.getStream(), contentType, content.getName())));
                }
            }
            if (parts.size() > 0) {
                MultipartEntity entity = new MultipartEntity(HttpMultipartMode.STRICT);
                for (FormBodyPart p : parts) {
                    entity.addPart(p);
                }
                postOrPut.setEntity(entity);
            } else {
                //not using multipart
                postOrPut.setEntity(new UrlEncodedFormEntity(postOrPutParams, StandardCharsets.UTF_8));
            }
            return postOrPut;
        } else // It is has one stream, it is the post body, put the params in the URL
        {
            String fullQueryUrl = url + wparams.toQueryString();
            HttpEntityEnclosingRequestBase postOrPut = SolrRequest.METHOD.POST == request.getMethod() ? new HttpPost(fullQueryUrl) : new HttpPut(fullQueryUrl);
            // Single stream as body
            // Using a loop just to get the first one
            final ContentStream[] contentStream = new ContentStream[1];
            for (ContentStream content : streams) {
                contentStream[0] = content;
                break;
            }
            if (contentStream[0] instanceof RequestWriter.LazyContentStream) {
                Long size = contentStream[0].getSize();
                postOrPut.setEntity(new InputStreamEntity(contentStream[0].getStream(), size == null ? -1 : size) {

                    @Override
                    public Header getContentType() {
                        return new BasicHeader("Content-Type", contentStream[0].getContentType());
                    }

                    @Override
                    public boolean isRepeatable() {
                        return false;
                    }
                });
            } else {
                Long size = contentStream[0].getSize();
                postOrPut.setEntity(new InputStreamEntity(contentStream[0].getStream(), size == null ? -1 : size) {

                    @Override
                    public Header getContentType() {
                        return new BasicHeader("Content-Type", contentStream[0].getContentType());
                    }

                    @Override
                    public boolean isRepeatable() {
                        return false;
                    }
                });
            }
            return postOrPut;
        }
    }
    throw new SolrServerException("Unsupported method: " + request.getMethod());
}
Also used : HttpPost(org.apache.http.client.methods.HttpPost) ResponseParser(org.apache.solr.client.solrj.ResponseParser) HttpDelete(org.apache.http.client.methods.HttpDelete) HttpGet(org.apache.http.client.methods.HttpGet) SolrServerException(org.apache.solr.client.solrj.SolrServerException) ModifiableSolrParams(org.apache.solr.common.params.ModifiableSolrParams) HttpPut(org.apache.http.client.methods.HttpPut) FormBodyPart(org.apache.http.entity.mime.FormBodyPart) ContentStream(org.apache.solr.common.util.ContentStream) MultipartEntity(org.apache.http.entity.mime.MultipartEntity) BasicNameValuePair(org.apache.http.message.BasicNameValuePair) InputStreamBody(org.apache.http.entity.mime.content.InputStreamBody) SolrException(org.apache.solr.common.SolrException) NameValuePair(org.apache.http.NameValuePair) BasicNameValuePair(org.apache.http.message.BasicNameValuePair) HttpEntityEnclosingRequestBase(org.apache.http.client.methods.HttpEntityEnclosingRequestBase) UrlEncodedFormEntity(org.apache.http.client.entity.UrlEncodedFormEntity) V2Request(org.apache.solr.client.solrj.request.V2Request) LinkedList(java.util.LinkedList) InputStreamEntity(org.apache.http.entity.InputStreamEntity) Header(org.apache.http.Header) BasicHeader(org.apache.http.message.BasicHeader) StringBody(org.apache.http.entity.mime.content.StringBody) SolrParams(org.apache.solr.common.params.SolrParams) ModifiableSolrParams(org.apache.solr.common.params.ModifiableSolrParams) BasicHeader(org.apache.http.message.BasicHeader)

Aggregations

HttpEntityEnclosingRequestBase (org.apache.http.client.methods.HttpEntityEnclosingRequestBase)39 HttpPost (org.apache.http.client.methods.HttpPost)17 IOException (java.io.IOException)9 HttpPut (org.apache.http.client.methods.HttpPut)9 HttpEntity (org.apache.http.HttpEntity)7 HttpResponse (org.apache.http.HttpResponse)6 InputStream (java.io.InputStream)5 Header (org.apache.http.Header)5 NameValuePair (org.apache.http.NameValuePair)5 HttpRequestBase (org.apache.http.client.methods.HttpRequestBase)5 StringEntity (org.apache.http.entity.StringEntity)5 File (java.io.File)4 CloseableHttpResponse (org.apache.http.client.methods.CloseableHttpResponse)4 HashMap (java.util.HashMap)3 HttpDelete (org.apache.http.client.methods.HttpDelete)3 HttpGet (org.apache.http.client.methods.HttpGet)3 FileEntity (org.apache.http.entity.FileEntity)3 OutputStream (java.io.OutputStream)2 URI (java.net.URI)2 LinkedList (java.util.LinkedList)2