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

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

Introduction

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

Prototype

public HttpEntity getEntity() 

Source Link

Usage

From source file:com.betfair.testing.utils.cougar.manager.CougarManagerTest.java

@Test
public void sendPostRestRequest_Test() throws ParserConfigurationException, SAXException, IOException {

    String POSTQUERY = "<ComplexObject><name>sum</name><value1>7</value1><value2>75</value2></ComplexObject>";

    //String expRestXMLRequestBody = "<ComplexObject xmlns=\"http://www.betfair.com/servicetypes/v2/Baseline/\"><name>sum</name><value1>7</value1><value2>75</value2></ComplexObject>";
    String operationName = "someOperation";
    String requestWrapper = "SomeOperationRequest";

    String expRestXMLRequestBody = "<" + requestWrapper
            + " xmlns=\"http://www.betfair.com/servicetypes/v2/Baseline/\"><complexObject><name>sum</name><value1>7</value1><value2>75</value2></complexObject></"
            + requestWrapper + ">";

    //String expRestJSONRequestBody = "{\"name\":\"sum\",\"value1\":7,\"value2\":75}" ;
    String expRestJSONRequestBody = "{\"complexObject\":{\"name\":\"sum\",\"value1\":7,\"value2\":75}}";

    DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance();
    DocumentBuilder builder = factory.newDocumentBuilder();
    Document document = builder.parse(new InputSource(new StringReader(POSTQUERY)));

    HttpCallBean httpCallBean = new HttpCallBean();

    httpCallBean.setOperationName(operationName);
    httpCallBean.setServiceName("Baseline");
    httpCallBean.setVersion("v2");
    httpCallBean.setQueryParams(null);/* w w  w.  j  av a 2s  .c o  m*/
    httpCallBean.setHeaderParams(null);

    httpCallBean.setRestPostQueryObjects(document);

    cougarManager.makeRestCougarHTTPCalls(httpCallBean);

    List<HttpUriRequest> methodsSent = cougarTestDAO.methods;

    HttpPost methodSent;

    methodSent = (HttpPost) methodsSent.get(0);

    assertNull(methodSent.getURI().getQuery());

    assertEquals("/Baseline/v2/" + operationName, methodSent.getURI().getPath());

    Header[] headers = methodSent.getAllHeaders();
    assertEquals(4, headers.length);

    assertEquals("Content-Type: application/json", String.valueOf(headers[0]));
    assertEquals("User-Agent: java/socket", String.valueOf(headers[1]));
    assertEquals("Accept: application/json", String.valueOf(headers[2]));
    //Changed this from 37...
    //assertEquals("Content-Length: 55", String.valueOf(headers[3]));
    assertEquals("X-Forwarded-For: 87.248.113.14", String.valueOf(headers[3]));

    StringEntity stringRequestEntity = (StringEntity) methodSent.getEntity();
    InputStream inputStream = stringRequestEntity.getContent();
    byte[] buffer = new byte[inputStream.available()];
    int offset = 0;
    int read;
    while ((read = inputStream.read(buffer, offset, inputStream.available())) != -1) {
        offset += read;
    }
    assertEquals(expRestJSONRequestBody, new String(buffer, "UTF-8"));

    methodSent = (HttpPost) methodsSent.get(2);

    assertNull(methodSent.getURI().getQuery());

    assertEquals("/Baseline/v2/" + operationName, methodSent.getURI().getPath());

    headers = methodSent.getAllHeaders();
    assertEquals(4, headers.length);

    stringRequestEntity = (StringEntity) methodSent.getEntity();
    inputStream = stringRequestEntity.getContent();
    buffer = new byte[inputStream.available()];
    offset = 0;
    while ((read = inputStream.read(buffer, offset, inputStream.available())) != -1) {
        offset += read;
    }
    assertEquals(expRestXMLRequestBody, new String(buffer, "UTF-8"));

    assertEquals("Content-Type: application/xml", String.valueOf(headers[0]));
    assertEquals("User-Agent: java/socket", String.valueOf(headers[1]));
    assertEquals("Accept: application/xml", String.valueOf(headers[2]));

    //assertEquals("Content-Length: 141", String.valueOf(headers[3]));
    //assertEquals("Content-Length: 186", String.valueOf(headers[3]));

    assertEquals("X-Forwarded-For: 87.248.113.14", String.valueOf(headers[3]));

}

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

@Test
public void addPageUnderAncestorRequest_withAncestorId_returnsValidHttpPostWithAncestorIdWithoutSpaceKey()
        throws Exception {
    // arrange//from w  w  w.j a  va 2 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 addAttachmentRequest_withValidParameters_returnsValidHttpPostWithMultipartEntity()
        throws Exception {
    // arrange// w  ww .j a v  a2s  .  c  om
    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:autopostsoicomputer.API.WPApi.java

@Override
public void createNewPostWP(PostObject po, String strUrlWordpress)
        throws UnsupportedEncodingException, IOException {
    strUrlWordpress += "createpost.php";
    for (;;) {//  ww  w.ja  va2s . c om
        try {
            HttpClient client = new DefaultHttpClient();

            ////// Get Variable
            String strPostTitle = po.getPostTitle();
            // check if postTitle has posted

            String strPostImageFeature = po.getPostImageFeature();
            String strPostCategory = po.getPostCategory();
            String strPostContent = po.getPostContent();
            //////
            HttpPost post = new HttpPost(strUrlWordpress);

            // add header
            post.setHeader("User-Agent", "PosterBotDefault");

            List<NameValuePair> urlParameters = new ArrayList<NameValuePair>();
            urlParameters.add(new BasicNameValuePair("user", USER));
            urlParameters.add(new BasicNameValuePair("pass", PASS));
            urlParameters.add(new BasicNameValuePair("post_title", strPostTitle));
            urlParameters.add(new BasicNameValuePair("cat", strPostCategory));
            urlParameters.add(new BasicNameValuePair("post_content", strPostContent));
            urlParameters.add(new BasicNameValuePair("image_future", strPostImageFeature));

            post.setEntity(new UrlEncodedFormEntity(urlParameters, "UTF-8"));
            HttpResponse response = client.execute(post);
            System.out.println("\nSending 'POST' request to URL : " + strUrlWordpress);
            System.out.println("Post parameters : " + post.getEntity());
            System.out.println("Response Code : " + response.getStatusLine().getStatusCode());

            BufferedReader rd = new BufferedReader(new InputStreamReader(response.getEntity().getContent()));

            StringBuffer result = new StringBuffer();
            String line = "";
            while ((line = rd.readLine()) != null) {
                result.append(line);
            }

            System.out.println(result.toString());
            if (response.getStatusLine().getStatusCode() == 200) {
                ReaderFactory.getInstance().writeFile(strPostTitle);
            }
        } catch (Exception ex) {
            System.out.println("ERROR CREATE POST : " + ex.toString());
            count_getPost++;
            if (count_getPost == maxTries_getPost) {
                System.out.println("I TRY CREATE POST TO!!! " + strUrlWordpress);
                count_getPost = 0;
                break;
            } else {
                System.out.println("TRY TIMES  : " + count_getPost);
                createNewPostWP(po, strUrlWordpress);
            }
        } finally {
            break;
        }
    }
}

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

@Test
public void updateAttachmentContentRequest_withValidParameters_returnsHttpPutRequestWithMultipartEntity()
        throws Exception {
    // arrange//from   w  w  w.  j  a va 2s.  com
    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:org.wikipedia.vlsergey.secretary.jwpf.HttpBot.java

private void onPostResponse(final ContentProcessable action, final HttpPost postMethod, HttpResponse response)
        throws IOException {
    try {/*from  ww  w . j av a2 s.  c  o  m*/
        int statuscode = response.getStatusLine().getStatusCode();
        if (action.followRedirects() && (statuscode == HttpStatus.SC_MOVED_TEMPORARILY
                || statuscode == HttpStatus.SC_MOVED_PERMANENTLY || statuscode == HttpStatus.SC_SEE_OTHER
                || statuscode == HttpStatus.SC_TEMPORARY_REDIRECT)) {
            /*
             * Usually a successful form-based login results in a redicrect
             * to another url
             */
            Header header = response.getFirstHeader("location");
            if (header != null) {
                String newuri = header.getValue();
                if ((newuri == null) || (newuri.equals(""))) {
                    newuri = "/";
                }
                log.debug("Redirect target: " + newuri);

                HttpPost redirect = new HttpPost(newuri);
                redirect.setEntity(postMethod.getEntity());
                redirect.setHeader("Accept-Encoding", GZIP_CONTENT_ENCODING);
                log.trace("GET: " + redirect.getURI());
                httpClient.execute(redirect, new ResponseHandler<Object>() {
                    @Override
                    public Object handleResponse(HttpResponse response)
                            throws ClientProtocolException, IOException {
                        // no more redirects?
                        onPostResponse(action, postMethod, response);
                        return null;
                    }
                });
                return;
            }
        }

        if (statuscode == HttpStatus.SC_INTERNAL_SERVER_ERROR) {
            throw new ServerErrorException(response.getStatusLine());
        }
        if (statuscode != HttpStatus.SC_OK) {
            throw new ClientProtocolException(response.getStatusLine().toString());
        }

        final Header databaseLag = response.getFirstHeader("X-Database-Lag");
        final Header retryAfter = response.getFirstHeader("Retry-After");
        if (databaseLag != null) {
            throw new DatabaseLagException(databaseLag, retryAfter);
        }

        InputStream inputStream = response.getEntity().getContent();
        String out;
        try {
            String encoding = response.getFirstHeader("Content-Encoding") != null
                    ? response.getFirstHeader("Content-Encoding").getValue()
                    : "";
            if (GZIP_CONTENT_ENCODING.equalsIgnoreCase(encoding)) {
                inputStream = new GZIPInputStream(inputStream);
            }

            Header charsetHeader = response.getFirstHeader("Content-Type");
            String charset;
            if (charsetHeader == null)
                charset = MediaWikiBot.ENCODING;
            else
                charset = getContentCharSet(charsetHeader);

            out = IoUtils.readToString(inputStream, charset);
        } finally {
            inputStream.close();
        }

        action.processReturningText(postMethod, out);

        action.validateReturningCookies(httpClient.getCookieStore().getCookies(), postMethod);

        log.trace(postMethod.getURI() + " || " + "POST: " + response.getStatusLine().toString());
    } catch (CookieException exc) {
        throw new ClientProtocolException(exc.getMessage(), exc);
    } catch (ProcessException exc) {
        throw new ClientProtocolException(exc.getMessage(), exc);
    }
}

From source file:com.imaginary.home.device.hue.HueMethod.java

public JSONObject post(@Nonnull String resource, JSONObject body) throws HueException {
    Logger std = Hue.getLogger(HueMethod.class);
    Logger wire = Hue.getWireLogger(HueMethod.class);

    if (std.isTraceEnabled()) {
        std.trace("enter - " + HueMethod.class.getName() + ".post(" + resource + ")");
    }//from  w ww  . ja  v a2 s . co m
    if (wire.isDebugEnabled()) {
        wire.debug("");
        wire.debug(">>> [POST (" + (new Date()) + ")] -> " + hue.getAPIEndpoint() + resource);
    }
    try {
        HttpClient client = getClient();
        HttpPost method = new HttpPost(hue.getAPIEndpoint() + resource);

        method.addHeader("Content-Type", "application/json");

        try {
            if (body != null) {
                //noinspection deprecation
                method.setEntity(new StringEntity(body.toString(), "application/json", "UTF-8"));
            }
        } catch (UnsupportedEncodingException e) {
            throw new HueException(e);
        }
        if (wire.isDebugEnabled()) {
            wire.debug(method.getRequestLine().toString());
            for (Header header : method.getAllHeaders()) {
                wire.debug(header.getName() + ": " + header.getValue());
            }
            wire.debug("");
            if (body != null) {
                try {
                    wire.debug(EntityUtils.toString(method.getEntity()));
                } catch (IOException ignore) {
                }

                wire.debug("");
            }
        }
        HttpResponse response;
        StatusLine status;

        try {
            response = client.execute(method);
            status = response.getStatusLine();
        } catch (IOException e) {
            std.error("POST: Failed to execute HTTP request due to a cloud I/O error: " + e.getMessage());
            if (std.isTraceEnabled()) {
                e.printStackTrace();
            }
            throw new HueException(e);
        }
        if (std.isDebugEnabled()) {
            std.debug("POST: HTTP Status " + status);
        }
        Header[] headers = response.getAllHeaders();

        if (wire.isDebugEnabled()) {
            wire.debug(status.toString());
            for (Header h : headers) {
                if (h.getValue() != null) {
                    wire.debug(h.getName() + ": " + h.getValue().trim());
                } else {
                    wire.debug(h.getName() + ":");
                }
            }
            wire.debug("");
        }
        if (status.getStatusCode() != HttpServletResponse.SC_OK
                && status.getStatusCode() != HttpServletResponse.SC_CREATED
                && status.getStatusCode() != HttpServletResponse.SC_ACCEPTED) {
            std.error(
                    "POST: Expected CREATED or OK or ACCEPTED for POST request, got " + status.getStatusCode());

            HttpEntity entity = response.getEntity();

            if (entity == null) {
                throw new HueException(status.getStatusCode(), "An error was returned without explanation");
            }
            String json;

            try {
                json = EntityUtils.toString(entity);
            } catch (IOException e) {
                throw new HueException(status.getStatusCode(), e.getMessage());
            }
            if (wire.isDebugEnabled()) {
                wire.debug(json);
                wire.debug("");
            }
            throw new HueException(status.getStatusCode(), json);
        } else {
            try {
                String json = EntityUtils.toString(response.getEntity());

                if (wire.isDebugEnabled()) {
                    wire.debug(json);
                    wire.debug("");
                }
                if (json.startsWith("[")) {
                    JSONArray arr = new JSONArray(json);

                    if (arr.length() > 0) {
                        JSONObject ob = arr.getJSONObject(0);

                        if (ob.has("error")) {
                            ob = ob.getJSONObject("error");
                            if (ob.has("description")) {
                                throw new HueException(ob.getString("description"));
                            }
                        }
                        return ob;
                    }
                    return null;
                }
                return new JSONObject(json);
            } catch (IOException e) {
                throw new HueException(status.getStatusCode(), e.getMessage());
            } catch (JSONException e) {
                throw new HueException(status.getStatusCode(), e.getMessage());
            }
        }
    } finally {
        if (std.isTraceEnabled()) {
            std.trace("exit - " + HueMethod.class.getName() + ".post()");
        }
        if (wire.isDebugEnabled()) {
            wire.debug("<<< [POST (" + (new Date()) + ")] -> " + hue.getAPIEndpoint() + resource
                    + " <--------------------------------------------------------------------------------------");
            wire.debug("");
        }
    }
}