Search in sources :

Example 61 with StringRequestEntity

use of org.apache.commons.httpclient.methods.StringRequestEntity in project camel by apache.

the class UndertowMethodRestricTest method testProperHttpMethod.

@Test
public void testProperHttpMethod() throws Exception {
    HttpClient httpClient = new HttpClient();
    PostMethod httpPost = new PostMethod(url);
    StringRequestEntity reqEntity = new StringRequestEntity("This is a test", null, null);
    httpPost.setRequestEntity(reqEntity);
    int status = httpClient.executeMethod(httpPost);
    assertEquals(200, status);
    String result = httpPost.getResponseBodyAsString();
    assertEquals("This is a test response", result);
}
Also used : StringRequestEntity(org.apache.commons.httpclient.methods.StringRequestEntity) PostMethod(org.apache.commons.httpclient.methods.PostMethod) HttpClient(org.apache.commons.httpclient.HttpClient) Test(org.junit.Test)

Example 62 with StringRequestEntity

use of org.apache.commons.httpclient.methods.StringRequestEntity in project openhab1-addons by openhab.

the class Connection method sendCommand.

/**
     * Send a command to the Particle REST API (convenience function).
     *
     * @param device
     *            the device context, or <code>null</code> if not needed for this command.
     * @param funcName
     *            the function name to call, or variable/field to retrieve if <code>command</code> is
     *            <code>null</code>.
     * @param user
     *            the user name to use in Basic Authentication if the funcName would require Basic Authentication.
     * @param pass
     *            the password to use in Basic Authentication if the funcName would require Basic Authentication.
     * @param command
     *            the command to send to the API.
     * @param proc
     *            a callback object that receives the status code and response body, or <code>null</code> if not
     *            needed.
     */
public void sendCommand(AbstractDevice device, String funcName, String user, String pass, String command, HttpResponseHandler proc) {
    String url = null;
    String httpMethod = null;
    String content = null;
    String contentType = null;
    Properties headers = new Properties();
    logger.trace("sendCommand: funcName={}", funcName);
    switch(funcName) {
        case "createToken":
            httpMethod = HTTP_POST;
            url = TOKEN_URL;
            content = command;
            contentType = APPLICATION_FORM_URLENCODED;
            break;
        case "deleteToken":
            httpMethod = HTTP_DELETE;
            url = String.format(ACCESS_TOKENS_URL, tokens.accessToken);
            break;
        case "getDevices":
            httpMethod = HTTP_GET;
            url = String.format(GET_DEVICES_URL, tokens.accessToken);
            break;
        default:
            url = String.format(DEVICE_FUNC_URL, device.getId(), funcName, tokens.accessToken);
            if (command == null) {
                // retrieve a variable
                httpMethod = HTTP_GET;
            } else {
                // call a function
                httpMethod = HTTP_POST;
                content = command;
                contentType = APPLICATION_JSON;
            }
            break;
    }
    HttpClient client = new HttpClient();
    if (!url.contains("access_token=")) {
        Credentials credentials = new UsernamePasswordCredentials(user, pass);
        client.getParams().setAuthenticationPreemptive(true);
        client.getState().setCredentials(AuthScope.ANY, credentials);
    }
    HttpMethod method = createHttpMethod(httpMethod, url);
    method.getParams().setSoTimeout(timeout);
    method.getParams().setParameter(HttpMethodParams.RETRY_HANDLER, new DefaultHttpMethodRetryHandler(3, false));
    for (String httpHeaderKey : headers.stringPropertyNames()) {
        method.addRequestHeader(new Header(httpHeaderKey, headers.getProperty(httpHeaderKey)));
        logger.trace("Header key={}, value={}", httpHeaderKey, headers.getProperty(httpHeaderKey));
    }
    try {
        // add content if a valid method is given ...
        if (method instanceof EntityEnclosingMethod && content != null) {
            EntityEnclosingMethod eeMethod = (EntityEnclosingMethod) method;
            eeMethod.setRequestEntity(new StringRequestEntity(content, contentType, null));
            logger.trace("content='{}', contentType='{}'", content, contentType);
        }
        if (logger.isDebugEnabled()) {
            try {
                logger.debug("About to execute '{}'", method.getURI());
            } catch (URIException e) {
                logger.debug(e.getMessage());
            }
        }
        int statusCode = client.executeMethod(method);
        if (statusCode >= HttpStatus.SC_BAD_REQUEST) {
            logger.debug("Method failed: " + method.getStatusLine());
        }
        String responseBody = IOUtils.toString(method.getResponseBodyAsStream());
        if (!responseBody.isEmpty()) {
            logger.debug("Body of response: {}", responseBody);
        }
        if (proc != null) {
            proc.handleResponse(statusCode, responseBody);
        }
    } catch (HttpException he) {
        logger.warn("{}", he);
    } catch (IOException ioe) {
        logger.debug("{}", ioe);
    } finally {
        method.releaseConnection();
    }
}
Also used : StringRequestEntity(org.apache.commons.httpclient.methods.StringRequestEntity) EntityEnclosingMethod(org.apache.commons.httpclient.methods.EntityEnclosingMethod) DefaultHttpMethodRetryHandler(org.apache.commons.httpclient.DefaultHttpMethodRetryHandler) IOException(java.io.IOException) Properties(java.util.Properties) UsernamePasswordCredentials(org.apache.commons.httpclient.UsernamePasswordCredentials) URIException(org.apache.commons.httpclient.URIException) Header(org.apache.commons.httpclient.Header) HttpClient(org.apache.commons.httpclient.HttpClient) HttpException(org.apache.commons.httpclient.HttpException) UsernamePasswordCredentials(org.apache.commons.httpclient.UsernamePasswordCredentials) Credentials(org.apache.commons.httpclient.Credentials) HttpMethod(org.apache.commons.httpclient.HttpMethod)

Example 63 with StringRequestEntity

use of org.apache.commons.httpclient.methods.StringRequestEntity in project camel by apache.

the class HttpRouteTest method testPostXMLMessage.

@Test
public void testPostXMLMessage() throws Exception {
    HttpClient client = new HttpClient();
    PostMethod post = new PostMethod("http://localhost:" + port1 + "/postxml");
    StringRequestEntity entity = new StringRequestEntity(POST_MESSAGE, "application/xml", "UTF-8");
    post.setRequestEntity(entity);
    client.executeMethod(post);
    InputStream response = post.getResponseBodyAsStream();
    String out = context.getTypeConverter().convertTo(String.class, response);
    assertEquals("Get a wrong output ", "OK", out);
}
Also used : StringRequestEntity(org.apache.commons.httpclient.methods.StringRequestEntity) PostMethod(org.apache.commons.httpclient.methods.PostMethod) ByteArrayInputStream(java.io.ByteArrayInputStream) InputStream(java.io.InputStream) HttpClient(org.apache.commons.httpclient.HttpClient) Test(org.junit.Test)

Example 64 with StringRequestEntity

use of org.apache.commons.httpclient.methods.StringRequestEntity in project zm-mailbox by Zimbra.

the class ElasticSearchConnector method executeMethod.

public int executeMethod(HttpMethod method) throws IndexStoreException, IOException {
    String reqBody = "";
    if (ZimbraLog.elasticsearch.isTraceEnabled() && method instanceof EntityEnclosingMethod) {
        EntityEnclosingMethod eem = (EntityEnclosingMethod) method;
        RequestEntity re = eem.getRequestEntity();
        if (re instanceof StringRequestEntity) {
            StringRequestEntity sre = (StringRequestEntity) re;
            reqBody = Strings.nullToEmpty(sre.getContent());
            if (reqBody.length() > 0) {
                reqBody = String.format("\nREQUEST BODY=%s", reqBody);
            }
        }
    }
    try {
        HttpClient client = ZimbraHttpConnectionManager.getInternalHttpConnMgr().newHttpClient();
        statusCode = client.executeMethod(method);
    } catch (ConnectException ce) {
        throw new ZimbraElasticSearchDownException(ce);
    } catch (NoHttpResponseException nhre) {
        // them after retrying a number of times.
        throw new ZimbraElasticSearchNoResponseException(nhre);
    }
    body = method.getResponseBodyAsString();
    ZimbraLog.elasticsearch.trace("ElasticSearch request:%s %s - statusCode=%d%s\nRESPONSE BODY=%s", method.getName(), method.getURI(), statusCode, reqBody, body);
    return statusCode;
}
Also used : NoHttpResponseException(org.apache.commons.httpclient.NoHttpResponseException) StringRequestEntity(org.apache.commons.httpclient.methods.StringRequestEntity) EntityEnclosingMethod(org.apache.commons.httpclient.methods.EntityEnclosingMethod) HttpClient(org.apache.commons.httpclient.HttpClient) StringRequestEntity(org.apache.commons.httpclient.methods.StringRequestEntity) RequestEntity(org.apache.commons.httpclient.methods.RequestEntity) ConnectException(java.net.ConnectException)

Example 65 with StringRequestEntity

use of org.apache.commons.httpclient.methods.StringRequestEntity in project Mvp-Rxjava-Retrofit-dagger2 by pengMaster.

the class MediaRecordPresenter method downLoadRelationMedia.

/**
 * 下载关联视频
 *
 * @param taken
 * @param recorderCode
 */
private void downLoadRelationMedia(final String recorderCode, final String taken, final String id) {
    ThreadUtils.runThread(new Runnable() {

        @Override
        public void run() {
            HttpClient httpClient = new HttpClient();
            Map msg = new HashMap();
            msg.put("recorderCode", recorderCode);
            // msg.put("startDate", "2017-01-25 00:00:00");
            // msg.put("endDate", "2017-10-25 23:59:59");
            String params = new Gson().toJson(msg);
            StringRequestEntity paramEntity = null;
            try {
                paramEntity = new StringRequestEntity(params, "application/json", "utf-8");
            } catch (UnsupportedEncodingException e) {
                e.printStackTrace();
            }
            PostMethod postMethod = new PostMethod(Api.GET_RELATION_MEDIA + "?token=" + taken);
            postMethod.setRequestEntity(paramEntity);
            try {
                httpClient.executeMethod(postMethod);
            } catch (IOException e) {
                e.printStackTrace();
            }
            try {
                InputStream inputStream = postMethod.getResponseBodyAsStream();
                final String relationMedia = convertStreamToString(inputStream);
                ThreadUtils.runInMainThread(new Runnable() {

                    @Override
                    public void run() {
                        Bundle bundle = new Bundle();
                        bundle.putString("resultRelationMedia", relationMedia);
                        bundle.putString("superviseId", id);
                        bundle.putString("recorderCode", recorderCode);
                        mRootView.startRelationMedia(bundle);
                    }
                });
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
    });
}
Also used : StringRequestEntity(org.apache.commons.httpclient.methods.StringRequestEntity) HashMap(java.util.HashMap) PostMethod(org.apache.commons.httpclient.methods.PostMethod) InputStream(java.io.InputStream) Bundle(android.os.Bundle) Gson(com.google.gson.Gson) UnsupportedEncodingException(java.io.UnsupportedEncodingException) IOException(java.io.IOException) HttpClient(org.apache.commons.httpclient.HttpClient) Map(java.util.Map) HashMap(java.util.HashMap)

Aggregations

StringRequestEntity (org.apache.commons.httpclient.methods.StringRequestEntity)102 PostMethod (org.apache.commons.httpclient.methods.PostMethod)63 HttpClient (org.apache.commons.httpclient.HttpClient)33 Test (org.junit.Test)23 PutMethod (org.apache.commons.httpclient.methods.PutMethod)19 RequestEntity (org.apache.commons.httpclient.methods.RequestEntity)18 IOException (java.io.IOException)15 UnsupportedEncodingException (java.io.UnsupportedEncodingException)13 AuthRequestHandler (org.apache.commons.httpclient.server.AuthRequestHandler)12 HttpRequestHandlerChain (org.apache.commons.httpclient.server.HttpRequestHandlerChain)12 HttpServiceHandler (org.apache.commons.httpclient.server.HttpServiceHandler)12 Header (org.apache.commons.httpclient.Header)9 UsernamePasswordCredentials (org.apache.commons.httpclient.UsernamePasswordCredentials)9 GetMethod (org.apache.commons.httpclient.methods.GetMethod)9 InputStream (java.io.InputStream)8 InputStreamRequestEntity (org.apache.commons.httpclient.methods.InputStreamRequestEntity)7 StringWriter (java.io.StringWriter)6 Map (java.util.Map)6 ByteArrayRequestEntity (org.apache.commons.httpclient.methods.ByteArrayRequestEntity)6 PutMethod (org.apache.jackrabbit.webdav.client.methods.PutMethod)6