Example usage for org.apache.commons.httpclient.methods StringRequestEntity StringRequestEntity

List of usage examples for org.apache.commons.httpclient.methods StringRequestEntity StringRequestEntity

Introduction

In this page you can find the example usage for org.apache.commons.httpclient.methods StringRequestEntity StringRequestEntity.

Prototype

public StringRequestEntity(String paramString1, String paramString2, String paramString3)
  throws UnsupportedEncodingException

Source Link

Usage

From source file:muki.tool.JavaCompilationDeploymentTestCase.java

@Test
public void testPostOperation11Json() throws Exception {
    String url = URL_RESOURCE1 + "/pathPostOperation11Json/21?page=31";
    PostMethod method = new PostMethod(url);
    String param = this.getJsonCd();
    method.setRequestEntity(new StringRequestEntity(param, "application/json", null));

    int statusCode = this.getHttpClient().executeMethod(method);
    assertTrue("Method failed: " + method.getStatusLine(), statusCode == HttpStatus.SC_OK);
    byte[] responseBody = method.getResponseBody();
    String jsonResponse = new String(responseBody);
    assertTrue(jsonResponse.indexOf("\"title\":\"postOperation11-21-31\"") > -1);
}

From source file:muki.tool.JavaCompilationDeploymentTestCase.java

@Test
public void testPostOperation12Xml() throws Exception {
    String url = URL_RESOURCE1 + "/pathPostOperation12Xml";
    PostMethod method = new PostMethod(url);
    String param = this.getXmlCd();
    method.setRequestEntity(new StringRequestEntity(param, "application/xml", null));

    int statusCode = this.getHttpClient().executeMethod(method);
    assertTrue("Method failed: " + method.getStatusLine(), statusCode == HttpStatus.SC_OK);
    byte[] responseBody = method.getResponseBody();
    String xmlResponse = new String(responseBody);
    assertTrue(xmlResponse.indexOf("<?xml version=\"1.0\" encoding=\"UTF-8\" standalone=\"yes\"?>") > -1);
    assertTrue(xmlResponse.indexOf("<title>My Track 1</title>") > -1);
}

From source file:com.adobe.share.api.ShareAPI.java

/**
 * Prepares a new HTTP request./*from  w  w  w  . j  av  a 2 s. c  o  m*/
 *
 * @param user the user
 * @param method the method
 * @param url the url
 * @param anon the anon
 * @param requestBody the request body
 *
 * @return the http method
 */
protected final HttpMethod createRequest(final ShareAPIUser user, final String method, final String url,
        final boolean anon, final String requestBody) {
    HttpMethod httpMethod = null;
    if ("GET".equals(method)) {
        httpMethod = new GetMethod(url);
    } else if ("POST".equals(method)) {
        httpMethod = new PostMethod(url);
        httpMethod.setRequestHeader("Content-Type", "application/x-www-form-urlencoded");
        try {
            ((PostMethod) httpMethod).setRequestEntity(new StringRequestEntity(requestBody, null, null));
        } catch (UnsupportedEncodingException uee) {
            // Catch the unsupported encoding exception
            LOGGER.error("Unsupported encoding exception: " + uee.getMessage());
        }
    } else if ("PUT".equals(method)) {
        httpMethod = new PutMethod(url);
        httpMethod.setRequestHeader("Content-Type", "text/plain");
        if (requestBody != null) {
            ((PutMethod) httpMethod).setRequestEntity(
                    new InputStreamRequestEntity(new ByteArrayInputStream(requestBody.getBytes())));
        }
    } else if ("DELETE".equals(method)) {
        httpMethod = new DeleteMethod(url);
    } else if ("HEAD".equals(method)) {
        httpMethod = new HeadMethod(url);
    }
    /**
     * MoveMethod not supported by HttpClient else if("MOVE".equals(method))
     * { httpMethod = new MoveMethod(url); }
     **/
    httpMethod.setRequestHeader("Authorization", generateAuthorization(user, anon, method, url));

    return httpMethod;
}

From source file:muki.tool.JavaCompilationDeploymentTestCase.java

@Test
public void testPostOperation12Json() throws Exception {
    String url = URL_RESOURCE1 + "/pathPostOperation12Json";
    PostMethod method = new PostMethod(url);
    String param = this.getJsonCd();
    method.setRequestEntity(new StringRequestEntity(param, "application/json", null));

    int statusCode = this.getHttpClient().executeMethod(method);
    assertTrue("Method failed: " + method.getStatusLine(), statusCode == HttpStatus.SC_OK);
    byte[] responseBody = method.getResponseBody();
    String jsonResponse = new String(responseBody);
    assertTrue(jsonResponse.indexOf("\"newRelease\":true") > -1);
    assertTrue(jsonResponse.indexOf("\"title\":\"My Track 1\"") > -1);
}

From source file:com.twelve.capital.external.feed.util.HttpImpl.java

protected byte[] URLtoByteArray(String location, Http.Method method, Map<String, String> headers,
        Cookie[] cookies, Http.Auth auth, Http.Body body, List<Http.FilePart> fileParts,
        Map<String, String> parts, Http.Response response, boolean followRedirects, String progressId,
        PortletRequest portletRequest) throws IOException {

    byte[] bytes = null;

    HttpMethod httpMethod = null;//  w w  w. ja  v a  2  s  . c om
    HttpState httpState = null;

    try {
        _cookies.set(null);

        if (location == null) {
            return null;
        } else if (!location.startsWith(Http.HTTP_WITH_SLASH) && !location.startsWith(Http.HTTPS_WITH_SLASH)) {

            location = Http.HTTP_WITH_SLASH + location;
        }

        HostConfiguration hostConfiguration = getHostConfiguration(location);

        HttpClient httpClient = getClient(hostConfiguration);

        if (method.equals(Http.Method.POST) || method.equals(Http.Method.PUT)) {

            if (method.equals(Http.Method.POST)) {
                httpMethod = new PostMethod(location);
            } else {
                httpMethod = new PutMethod(location);
            }

            if (body != null) {
                RequestEntity requestEntity = new StringRequestEntity(body.getContent(), body.getContentType(),
                        body.getCharset());

                EntityEnclosingMethod entityEnclosingMethod = (EntityEnclosingMethod) httpMethod;

                entityEnclosingMethod.setRequestEntity(requestEntity);
            } else if (method.equals(Http.Method.POST)) {
                PostMethod postMethod = (PostMethod) httpMethod;

                if (!hasRequestHeader(postMethod, HttpHeaders.CONTENT_TYPE)) {

                    HttpClientParams httpClientParams = httpClient.getParams();

                    httpClientParams.setParameter(HttpMethodParams.HTTP_CONTENT_CHARSET, StringPool.UTF8);
                }

                processPostMethod(postMethod, fileParts, parts);
            }
        } else if (method.equals(Http.Method.DELETE)) {
            httpMethod = new DeleteMethod(location);
        } else if (method.equals(Http.Method.HEAD)) {
            httpMethod = new HeadMethod(location);
        } else {
            httpMethod = new GetMethod(location);
        }

        if (headers != null) {
            for (Map.Entry<String, String> header : headers.entrySet()) {
                httpMethod.addRequestHeader(header.getKey(), header.getValue());
            }
        }

        if ((method.equals(Http.Method.POST) || method.equals(Http.Method.PUT)) && ((body != null)
                || ((fileParts != null) && !fileParts.isEmpty()) || ((parts != null) && !parts.isEmpty()))) {
        } else if (!hasRequestHeader(httpMethod, HttpHeaders.CONTENT_TYPE)) {
            httpMethod.addRequestHeader(HttpHeaders.CONTENT_TYPE,
                    ContentTypes.APPLICATION_X_WWW_FORM_URLENCODED_UTF8);
        }

        if (!hasRequestHeader(httpMethod, HttpHeaders.USER_AGENT)) {
            httpMethod.addRequestHeader(HttpHeaders.USER_AGENT, _DEFAULT_USER_AGENT);
        }

        httpState = new HttpState();

        if (ArrayUtil.isNotEmpty(cookies)) {
            org.apache.commons.httpclient.Cookie[] commonsCookies = toCommonsCookies(cookies);

            httpState.addCookies(commonsCookies);

            HttpMethodParams httpMethodParams = httpMethod.getParams();

            httpMethodParams.setCookiePolicy(CookiePolicy.BROWSER_COMPATIBILITY);
        }

        if (auth != null) {
            httpMethod.setDoAuthentication(true);

            httpState.setCredentials(new AuthScope(auth.getHost(), auth.getPort(), auth.getRealm()),
                    new UsernamePasswordCredentials(auth.getUsername(), auth.getPassword()));
        }

        proxifyState(httpState, hostConfiguration);

        int responseCode = httpClient.executeMethod(hostConfiguration, httpMethod, httpState);

        response.setResponseCode(responseCode);

        Header locationHeader = httpMethod.getResponseHeader("location");

        if ((locationHeader != null) && !locationHeader.equals(location)) {
            String redirect = locationHeader.getValue();

            if (followRedirects) {
                return URLtoByteArray(redirect, Http.Method.GET, headers, cookies, auth, body, fileParts, parts,
                        response, followRedirects, progressId, portletRequest);
            } else {
                response.setRedirect(redirect);
            }
        }

        InputStream inputStream = httpMethod.getResponseBodyAsStream();

        if (inputStream != null) {
            int contentLength = 0;

            Header contentLengthHeader = httpMethod.getResponseHeader(HttpHeaders.CONTENT_LENGTH);

            if (contentLengthHeader != null) {
                contentLength = GetterUtil.getInteger(contentLengthHeader.getValue());

                response.setContentLength(contentLength);
            }

            Header contentType = httpMethod.getResponseHeader(HttpHeaders.CONTENT_TYPE);

            if (contentType != null) {
                response.setContentType(contentType.getValue());
            }

            if (Validator.isNotNull(progressId) && (portletRequest != null)) {

                ProgressInputStream progressInputStream = new ProgressInputStream(portletRequest, inputStream,
                        contentLength, progressId);

                UnsyncByteArrayOutputStream unsyncByteArrayOutputStream = new UnsyncByteArrayOutputStream(
                        contentLength);

                try {
                    progressInputStream.readAll(unsyncByteArrayOutputStream);
                } finally {
                    progressInputStream.clearProgress();
                }

                bytes = unsyncByteArrayOutputStream.unsafeGetByteArray();

                unsyncByteArrayOutputStream.close();
            } else {
                bytes = FileUtil.getBytes(inputStream);
            }
        }

        for (Header header : httpMethod.getResponseHeaders()) {
            response.addHeader(header.getName(), header.getValue());
        }

        return bytes;
    } finally {
        try {
            if (httpState != null) {
                _cookies.set(toServletCookies(httpState.getCookies()));
            }
        } catch (Exception e) {
            _log.error(e, e);
        }

        try {
            if (httpMethod != null) {
                httpMethod.releaseConnection();
            }
        } catch (Exception e) {
            _log.error(e, e);
        }
    }
}

From source file:muki.tool.JavaCompilationDeploymentTestCase.java

@Test
public void testPostOperation13Json() throws Exception {
    String url = URL_RESOURCE1 + "/pathPostOperation13Json/artists/madonna/tracks/4";
    PostMethod method = new PostMethod(url);
    String param = this.getJsonCd();
    method.setRequestEntity(new StringRequestEntity(param, "application/json", null));

    int statusCode = this.getHttpClient().executeMethod(method);
    assertTrue("Method failed: " + method.getStatusLine(), statusCode == HttpStatus.SC_OK);
    byte[] responseBody = method.getResponseBody();
    String jsonResponse = new String(responseBody);
    assertTrue(jsonResponse.indexOf("\"title\":\"madonna-4\"") > -1);
}

From source file:muki.tool.JavaCompilationDeploymentTestCase.java

@Test
public void testPutOperation2() throws Exception {
    String url = URL_RESOURCE1 + "/pathPutOperation2";
    PutMethod method = new PutMethod(url);
    String param = "this is string parameter!";
    method.setRequestEntity(new StringRequestEntity(param, "application/xml", null));

    int statusCode = this.getHttpClient().executeMethod(method);
    assertTrue("Method failed: " + method.getStatusLine(), statusCode == HttpStatus.SC_NO_CONTENT);
    byte[] responseBody = method.getResponseBody();
    assertNull(responseBody);//  ww  w.j a  v  a 2s.c  o  m
}

From source file:muki.tool.JavaCompilationDeploymentTestCase.java

@Test
public void testPutOperation4() throws Exception {
    String url = URL_RESOURCE1 + "/pathPutOperation4";
    PutMethod method = new PutMethod(url);
    String param = "this is string parameter!";
    method.setRequestEntity(new StringRequestEntity(param, "application/xml", null));

    int statusCode = this.getHttpClient().executeMethod(method);
    assertTrue("Method failed: " + method.getStatusLine(), statusCode == HttpStatus.SC_OK);
    byte[] responseBody = method.getResponseBody();
    String actualResponse = new String(responseBody);
    String expectedResponse = "this is string parameter!";
    assertEquals(expectedResponse, actualResponse);
}

From source file:muki.tool.JavaCompilationDeploymentTestCase.java

@Test
public void testPutOperation5Xml() throws Exception {
    String url = URL_RESOURCE1 + "/pathPutOperation5Xml";
    PutMethod method = new PutMethod(url);
    String param = this.getXmlCd();
    method.setRequestEntity(new StringRequestEntity(param, "application/xml", null));

    int statusCode = this.getHttpClient().executeMethod(method);
    assertTrue("Method failed: " + method.getStatusLine(), statusCode == HttpStatus.SC_NO_CONTENT);
    byte[] responseBody = method.getResponseBody();
    assertNull(responseBody);/*from ww  w .  j ava2s .  com*/
}

From source file:muki.tool.JavaCompilationDeploymentTestCase.java

@Test
public void testPutOperation5Json() throws Exception {
    String url = URL_RESOURCE1 + "/pathPutOperation5Json";
    PutMethod method = new PutMethod(url);
    String param = this.getJsonCd();
    method.setRequestEntity(new StringRequestEntity(param, "application/json", null));

    int statusCode = this.getHttpClient().executeMethod(method);
    assertTrue("Method failed: " + method.getStatusLine(), statusCode == HttpStatus.SC_NO_CONTENT);
    byte[] responseBody = method.getResponseBody();
    assertNull(responseBody);//from   ww  w  .  ja  v  a2s .co  m
}