Search in sources :

Example 16 with StringRequestEntity

use of org.apache.commons.httpclient.methods.StringRequestEntity in project xwiki-platform by xwiki.

the class AbstractHttpTest method executePostXml.

protected PostMethod executePostXml(String uri, Object object) throws Exception {
    HttpClient httpClient = new HttpClient();
    PostMethod postMethod = new PostMethod(uri);
    postMethod.addRequestHeader("Accept", MediaType.APPLICATION_XML.toString());
    StringWriter writer = new StringWriter();
    marshaller.marshal(object, writer);
    RequestEntity entity = new StringRequestEntity(writer.toString(), MediaType.APPLICATION_XML.toString(), "UTF-8");
    postMethod.setRequestEntity(entity);
    httpClient.executeMethod(postMethod);
    return postMethod;
}
Also used : StringRequestEntity(org.apache.commons.httpclient.methods.StringRequestEntity) StringWriter(java.io.StringWriter) PostMethod(org.apache.commons.httpclient.methods.PostMethod) HttpClient(org.apache.commons.httpclient.HttpClient) RequestEntity(org.apache.commons.httpclient.methods.RequestEntity) InputStreamRequestEntity(org.apache.commons.httpclient.methods.InputStreamRequestEntity) StringRequestEntity(org.apache.commons.httpclient.methods.StringRequestEntity)

Example 17 with StringRequestEntity

use of org.apache.commons.httpclient.methods.StringRequestEntity in project xwiki-platform by xwiki.

the class AbstractHttpTest method executePutXml.

protected PutMethod executePutXml(String uri, Object object, String userName, String password) throws Exception {
    HttpClient httpClient = new HttpClient();
    httpClient.getState().setCredentials(AuthScope.ANY, new UsernamePasswordCredentials(userName, password));
    httpClient.getParams().setAuthenticationPreemptive(true);
    PutMethod putMethod = new PutMethod(uri);
    putMethod.addRequestHeader("Accept", MediaType.APPLICATION_XML.toString());
    StringWriter writer = new StringWriter();
    marshaller.marshal(object, writer);
    RequestEntity entity = new StringRequestEntity(writer.toString(), MediaType.APPLICATION_XML.toString(), "UTF-8");
    putMethod.setRequestEntity(entity);
    httpClient.executeMethod(putMethod);
    return putMethod;
}
Also used : StringRequestEntity(org.apache.commons.httpclient.methods.StringRequestEntity) StringWriter(java.io.StringWriter) HttpClient(org.apache.commons.httpclient.HttpClient) PutMethod(org.apache.commons.httpclient.methods.PutMethod) RequestEntity(org.apache.commons.httpclient.methods.RequestEntity) InputStreamRequestEntity(org.apache.commons.httpclient.methods.InputStreamRequestEntity) StringRequestEntity(org.apache.commons.httpclient.methods.StringRequestEntity) UsernamePasswordCredentials(org.apache.commons.httpclient.UsernamePasswordCredentials)

Example 18 with StringRequestEntity

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

the class ApacheHttpClient3Adapter method afterPreCap.

@Override
public void afterPreCap(InvokeChainContext context, Object[] args) {
    /**
     * after precap the client's span is created, set the span meta into http request header
     */
    String url = (String) context.get(InvokeChainConstants.CLIENT_SPAN_THREADLOCAL_STOREKEY);
    Span span = this.spanFactory.getSpanFromContext(url);
    String spanMeta = this.spanFactory.getSpanMeta(span);
    HttpMethod method = (HttpMethod) args[1];
    method.removeRequestHeader(InvokeChainConstants.PARAM_HTTPHEAD_SPANINFO);
    method.addRequestHeader(InvokeChainConstants.PARAM_HTTPHEAD_SPANINFO, spanMeta);
    if (UAVServer.instance().isExistSupportor("com.creditease.uav.apm.supporters.SlowOperSupporter")) {
        // httpclient3好像没有encoding参数
        SlowOperContext slowOperContext = new SlowOperContext();
        String quertParams = method.getQueryString();
        if (quertParams == null) {
            quertParams = "{}";
        }
        slowOperContext.put(SlowOperConstants.PROTOCOL_HTTP_HEADER, getHeadersContent(method.getRequestHeaders()) + quertParams);
        // 通过此种方式判断是否存在body,通过httpclient类继承确定
        String requestBody = "";
        if (EntityEnclosingMethod.class.isAssignableFrom(method.getClass())) {
            EntityEnclosingMethod entityMethod = (EntityEnclosingMethod) method;
            RequestEntity requestEntity = entityMethod.getRequestEntity();
            // 根据不同类型entity采取不同读取方式(由于httpclient3没有显视encoding,故此处使用默认的编码格式)
            if (ByteArrayRequestEntity.class.isAssignableFrom(requestEntity.getClass())) {
                requestBody = new String(((ByteArrayRequestEntity) requestEntity).getContent());
            } else if (InputStreamRequestEntity.class.isAssignableFrom(requestEntity.getClass())) {
                InputStreamRequestEntity inputStreamRequestEntity = (InputStreamRequestEntity) requestEntity;
                if (!inputStreamRequestEntity.isRepeatable()) {
                    inputStreamRequestEntity.getContentLength();
                }
                try {
                    BufferedReader reader = new BufferedReader(new InputStreamReader(inputStreamRequestEntity.getContent()));
                    StringBuilder body = new StringBuilder();
                    String str;
                    while ((str = reader.readLine()) != null) {
                        body.append(str);
                    }
                    requestBody = body.toString();
                } catch (UnsupportedOperationException e) {
                    logger.warn("body type is not supported!", e);
                    requestBody = "body type is not supported!" + e.toString();
                } catch (IOException e) {
                    logger.error("IOException!", e);
                    requestBody = e.toString();
                }
            } else if (MultipartRequestEntity.class.isAssignableFrom(requestEntity.getClass())) {
                // MultipartRequestEntity暂时不支持
                requestBody = "MultipartRequestEntity is not supported";
            } else if (StringRequestEntity.class.isAssignableFrom(requestEntity.getClass())) {
                requestBody = ((StringRequestEntity) requestEntity).getContent();
            } else {
                requestBody = "unsupported type";
            }
        }
        slowOperContext.put(SlowOperConstants.PROTOCOL_HTTP_BODY, requestBody);
        Object[] params = { span, slowOperContext };
        UAVServer.instance().runSupporter("com.creditease.uav.apm.supporters.SlowOperSupporter", "runCap", span.getEndpointInfo().split(",")[0], InvokeChainConstants.CapturePhase.PRECAP, context, params);
    }
}
Also used : SlowOperContext(com.creditease.uav.apm.slowoper.spi.SlowOperContext) InputStreamRequestEntity(org.apache.commons.httpclient.methods.InputStreamRequestEntity) StringRequestEntity(org.apache.commons.httpclient.methods.StringRequestEntity) InputStreamReader(java.io.InputStreamReader) EntityEnclosingMethod(org.apache.commons.httpclient.methods.EntityEnclosingMethod) IOException(java.io.IOException) Span(com.creditease.uav.apm.invokechain.span.Span) BufferedReader(java.io.BufferedReader) MultipartRequestEntity(org.apache.commons.httpclient.methods.multipart.MultipartRequestEntity) ByteArrayRequestEntity(org.apache.commons.httpclient.methods.ByteArrayRequestEntity) InputStreamRequestEntity(org.apache.commons.httpclient.methods.InputStreamRequestEntity) StringRequestEntity(org.apache.commons.httpclient.methods.StringRequestEntity) RequestEntity(org.apache.commons.httpclient.methods.RequestEntity) HttpMethod(org.apache.commons.httpclient.HttpMethod) ByteArrayRequestEntity(org.apache.commons.httpclient.methods.ByteArrayRequestEntity)

Example 19 with StringRequestEntity

use of org.apache.commons.httpclient.methods.StringRequestEntity in project spatial-portal by AtlasOfLivingAustralia.

the class BiocacheQuery method getGuid.

/**
 * Performs a scientific name or common name lookup and returns the guid if it exists in the BIE
 * <p/>
 * TODO Move getGuid and getClassification to BIE Utilities...
 *
 * @param name
 * @return
 */
public static String getGuid(String name) {
    if ("true".equalsIgnoreCase(CommonData.getSettings().getProperty("new.bie"))) {
        String url = CommonData.getBieServer() + "/ws/species/lookup/bulk";
        try {
            HttpClient client = new HttpClient();
            PostMethod get = new PostMethod(url);
            get.addRequestHeader(StringConstants.CONTENT_TYPE, StringConstants.APPLICATION_JSON);
            get.setRequestEntity(new StringRequestEntity("{\"names\":[\"" + name.replace("\"", "\\\"") + "\"]}"));
            client.executeMethod(get);
            String body = get.getResponseBodyAsString();
            JSONParser jp = new JSONParser();
            JSONArray ja = (JSONArray) jp.parse(body);
            if (ja != null && !ja.isEmpty()) {
                JSONObject jo = (JSONObject) ja.get(0);
                if (jo != null && jo.containsKey("acceptedIdentifier") && jo.get("acceptedIdentifier") != null) {
                    return jo.get("acceptedIdentifier").toString();
                } else if (jo != null && jo.containsKey("acceptedIdentifierGuid") && jo.get("acceptedIdentifierGuid") != null) {
                    return jo.get("acceptedIdentifierGuid").toString();
                } else if (jo != null && jo.containsKey("acceptedConceptID") && jo.get("acceptedConceptID") != null) {
                    return jo.get("acceptedConceptID").toString();
                } else if (jo != null && jo.containsKey("guid") && jo.get("guid") != null) {
                    return jo.get("guid").toString();
                } else {
                    return null;
                }
            } else {
                return null;
            }
        } catch (Exception e) {
            LOGGER.error("error getting guid at: " + url, e);
            return null;
        }
    } else {
        String url = CommonData.getBieServer() + "/ws/guid/" + name.replaceAll(" ", "%20");
        try {
            HttpClient client = new HttpClient();
            GetMethod get = new GetMethod(url);
            get.addRequestHeader(StringConstants.CONTENT_TYPE, StringConstants.APPLICATION_JSON);
            client.executeMethod(get);
            String body = get.getResponseBodyAsString();
            JSONParser jp = new JSONParser();
            JSONArray ja = (JSONArray) jp.parse(body);
            if (ja != null && !ja.isEmpty()) {
                JSONObject jo = (JSONObject) ja.get(0);
                if (jo != null && jo.containsKey("acceptedIdentifier") && jo.get("acceptedIdentifier") != null) {
                    return jo.get("acceptedIdentifier").toString();
                } else {
                    return null;
                }
            } else {
                return null;
            }
        } catch (Exception e) {
            LOGGER.error("error getting guid at: " + url, e);
            return null;
        }
    }
}
Also used : StringRequestEntity(org.apache.commons.httpclient.methods.StringRequestEntity) JSONObject(org.json.simple.JSONObject) PostMethod(org.apache.commons.httpclient.methods.PostMethod) HttpClient(org.apache.commons.httpclient.HttpClient) JSONArray(org.json.simple.JSONArray) GetMethod(org.apache.commons.httpclient.methods.GetMethod) JSONParser(org.json.simple.parser.JSONParser)

Example 20 with StringRequestEntity

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

the class TestEntityEnclosingMethod method testEmptyPostMethod.

public void testEmptyPostMethod() throws Exception {
    this.server.setHttpService(new RequestBodyStatsService());
    PostMethod method = new PostMethod("/");
    method.setRequestHeader("Content-Type", "text/plain");
    this.client.executeMethod(method);
    assertEquals(200, method.getStatusLine().getStatusCode());
    String response = method.getResponseBodyAsString();
    assertNotNull(method.getRequestHeader("Content-Length"));
    assertTrue(response.indexOf("No body submitted") >= 0);
    method = new PostMethod("/");
    method.setRequestHeader("Content-Type", "text/plain");
    method.setRequestEntity(new StringRequestEntity(""));
    this.client.executeMethod(method);
    assertEquals(200, method.getStatusLine().getStatusCode());
    assertNotNull(method.getRequestHeader("Content-Length"));
    response = method.getResponseBodyAsString();
    assertTrue(response.indexOf("No body submitted") >= 0);
    method = new PostMethod("/");
    method.setRequestHeader("Content-Type", "text/plain");
    method.setContentChunked(true);
    this.client.executeMethod(method);
    assertEquals(200, method.getStatusLine().getStatusCode());
    assertNotNull(method.getRequestHeader("Content-Length"));
    response = method.getResponseBodyAsString();
    assertTrue(response.indexOf("No body submitted") >= 0);
    method = new PostMethod("/");
    method.setRequestHeader("Content-Type", "text/plain");
    method.setRequestEntity(new StringRequestEntity(""));
    method.setContentChunked(true);
    this.client.executeMethod(method);
    assertNull(method.getRequestHeader("Content-Length"));
    assertNotNull(method.getRequestHeader("Transfer-Encoding"));
    assertEquals(200, method.getStatusLine().getStatusCode());
    response = method.getResponseBodyAsString();
    assertTrue(response.indexOf("No body submitted") >= 0);
}
Also used : StringRequestEntity(org.apache.commons.httpclient.methods.StringRequestEntity) PostMethod(org.apache.commons.httpclient.methods.PostMethod)

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