Search in sources :

Example 36 with StringEntity

use of org.apache.http.entity.StringEntity in project crate by crate.

the class BlobHttpIntegrationTest method put.

protected CloseableHttpResponse put(String uri, String body) throws IOException {
    HttpPut httpPut = new HttpPut(Blobs.url(address, uri));
    if (body != null) {
        StringEntity bodyEntity = new StringEntity(body);
        httpPut.setEntity(bodyEntity);
    }
    return executeAndDefaultAssertions(httpPut);
}
Also used : StringEntity(org.apache.http.entity.StringEntity)

Example 37 with StringEntity

use of org.apache.http.entity.StringEntity in project hive by apache.

the class JIRAService method publishComments.

void publishComments(String comments) {
    DefaultHttpClient httpClient = new DefaultHttpClient();
    try {
        String url = String.format("%s/rest/api/2/issue/%s/comment", mUrl, mName);
        URL apiURL = new URL(mUrl);
        httpClient.getCredentialsProvider().setCredentials(new AuthScope(apiURL.getHost(), apiURL.getPort(), AuthScope.ANY_REALM), new UsernamePasswordCredentials(mUser, mPassword));
        BasicHttpContext localcontext = new BasicHttpContext();
        localcontext.setAttribute("preemptive-auth", new BasicScheme());
        httpClient.addRequestInterceptor(new PreemptiveAuth(), 0);
        HttpPost request = new HttpPost(url);
        ObjectMapper mapper = new ObjectMapper();
        StringEntity params = new StringEntity(mapper.writeValueAsString(new Body(comments)));
        request.addHeader("Content-Type", "application/json");
        request.setEntity(params);
        HttpResponse httpResponse = httpClient.execute(request, localcontext);
        StatusLine statusLine = httpResponse.getStatusLine();
        if (statusLine.getStatusCode() != 201) {
            throw new RuntimeException(statusLine.getStatusCode() + " " + statusLine.getReasonPhrase());
        }
        mLogger.info("JIRA Response Metadata: " + httpResponse);
    } catch (Exception e) {
        mLogger.error("Encountered error attempting to post comment to " + mName, e);
    } finally {
        httpClient.getConnectionManager().shutdown();
    }
}
Also used : BasicScheme(org.apache.http.impl.auth.BasicScheme) HttpPost(org.apache.http.client.methods.HttpPost) BasicHttpContext(org.apache.http.protocol.BasicHttpContext) HttpResponse(org.apache.http.HttpResponse) DefaultHttpClient(org.apache.http.impl.client.DefaultHttpClient) URL(java.net.URL) IOException(java.io.IOException) HttpException(org.apache.http.HttpException) UsernamePasswordCredentials(org.apache.http.auth.UsernamePasswordCredentials) StatusLine(org.apache.http.StatusLine) StringEntity(org.apache.http.entity.StringEntity) AuthScope(org.apache.http.auth.AuthScope) ObjectMapper(org.codehaus.jackson.map.ObjectMapper)

Example 38 with StringEntity

use of org.apache.http.entity.StringEntity in project hive by apache.

the class PTestClient method post.

private <S extends GenericResponse> S post(Object payload, boolean agressiveRetry) throws Exception {
    EndPointResponsePair endPointResponse = Preconditions.checkNotNull(REQUEST_TO_ENDPOINT.get(payload.getClass()), payload.getClass().getName());
    HttpPost request = new HttpPost(mApiEndPoint + endPointResponse.getEndpoint());
    try {
        String payloadString = mMapper.writeValueAsString(payload);
        StringEntity params = new StringEntity(payloadString);
        request.addHeader("content-type", "application/json");
        request.setEntity(params);
        if (agressiveRetry) {
            mHttpClient.setHttpRequestRetryHandler(new PTestHttpRequestRetryHandler());
        }
        HttpResponse httpResponse = mHttpClient.execute(request);
        StatusLine statusLine = httpResponse.getStatusLine();
        if (statusLine.getStatusCode() != 200) {
            throw new IllegalStateException(statusLine.getStatusCode() + " " + statusLine.getReasonPhrase());
        }
        String response = EntityUtils.toString(httpResponse.getEntity(), "UTF-8");
        @SuppressWarnings("unchecked") S result = (S) endPointResponse.getResponseClass().cast(mMapper.readValue(response, endPointResponse.getResponseClass()));
        Status.assertOK(result.getStatus());
        if (System.getProperty("DEBUG_PTEST_CLIENT") != null) {
            System.err.println("payload " + payloadString);
            if (result instanceof TestLogResponse) {
                System.err.println("response " + ((TestLogResponse) result).getOffset() + " " + ((TestLogResponse) result).getStatus());
            } else {
                System.err.println("response " + response);
            }
        }
        Thread.sleep(1000);
        return result;
    } finally {
        request.abort();
    }
}
Also used : StatusLine(org.apache.http.StatusLine) HttpPost(org.apache.http.client.methods.HttpPost) StringEntity(org.apache.http.entity.StringEntity) TestLogResponse(org.apache.hive.ptest.api.response.TestLogResponse) HttpResponse(org.apache.http.HttpResponse)

Example 39 with StringEntity

use of org.apache.http.entity.StringEntity in project Android by hmkcode.

the class MainActivity method POST.

public static String POST(String url, Person person) {
    InputStream inputStream = null;
    String result = "";
    try {
        // 1. create HttpClient
        HttpClient httpclient = new DefaultHttpClient();
        // 2. make POST request to the given URL
        HttpPost httpPost = new HttpPost(url);
        String json = "";
        // 3. build jsonObject
        JSONObject jsonObject = new JSONObject();
        jsonObject.accumulate("name", person.getName());
        jsonObject.accumulate("country", person.getCountry());
        jsonObject.accumulate("twitter", person.getTwitter());
        // 4. convert JSONObject to JSON to String
        json = jsonObject.toString();
        // ** Alternative way to convert Person object to JSON string usin Jackson Lib 
        // ObjectMapper mapper = new ObjectMapper();
        // json = mapper.writeValueAsString(person); 
        // 5. set json to StringEntity
        StringEntity se = new StringEntity(json);
        // 6. set httpPost Entity
        httpPost.setEntity(se);
        // 7. Set some headers to inform server about the type of the content   
        httpPost.setHeader("Accept", "application/json");
        httpPost.setHeader("Content-type", "application/json");
        // 8. Execute POST request to the given URL
        HttpResponse httpResponse = httpclient.execute(httpPost);
        // 9. receive response as inputStream
        inputStream = httpResponse.getEntity().getContent();
        // 10. convert inputstream to string
        if (inputStream != null)
            result = convertInputStreamToString(inputStream);
        else
            result = "Did not work!";
    } catch (Exception e) {
        Log.d("InputStream", e.getLocalizedMessage());
    }
    // 11. return result
    return result;
}
Also used : HttpPost(org.apache.http.client.methods.HttpPost) StringEntity(org.apache.http.entity.StringEntity) JSONObject(org.json.JSONObject) InputStream(java.io.InputStream) DefaultHttpClient(org.apache.http.impl.client.DefaultHttpClient) HttpClient(org.apache.http.client.HttpClient) HttpResponse(org.apache.http.HttpResponse) DefaultHttpClient(org.apache.http.impl.client.DefaultHttpClient) IOException(java.io.IOException)

Example 40 with StringEntity

use of org.apache.http.entity.StringEntity in project pinot by linkedin.

the class DruidThroughput method main.

@SuppressWarnings("InfiniteLoopStatement")
public static void main(String[] args) throws Exception {
    final int numQueries = QUERIES.length;
    final Random random = new Random(RANDOM_SEED);
    final AtomicInteger counter = new AtomicInteger(0);
    final AtomicLong totalResponseTime = new AtomicLong(0L);
    final ExecutorService executorService = Executors.newFixedThreadPool(NUM_CLIENTS);
    for (int i = 0; i < NUM_CLIENTS; i++) {
        executorService.submit(new Runnable() {

            @Override
            public void run() {
                try (CloseableHttpClient client = HttpClients.createDefault()) {
                    HttpPost post = new HttpPost("http://localhost:8082/druid/v2/?pretty");
                    post.addHeader("content-type", "application/json");
                    CloseableHttpResponse res;
                    while (true) {
                        try (BufferedReader reader = new BufferedReader(new FileReader(QUERY_FILE_DIR + File.separator + random.nextInt(numQueries) + ".json"))) {
                            int length = reader.read(BUFFER);
                            post.setEntity(new StringEntity(new String(BUFFER, 0, length)));
                        }
                        long start = System.currentTimeMillis();
                        res = client.execute(post);
                        res.close();
                        counter.getAndIncrement();
                        totalResponseTime.getAndAdd(System.currentTimeMillis() - start);
                    }
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        });
    }
    long startTime = System.currentTimeMillis();
    while (true) {
        Thread.sleep(REPORT_INTERVAL_MILLIS);
        double timePassedSeconds = ((double) (System.currentTimeMillis() - startTime)) / MILLIS_PER_SECOND;
        int count = counter.get();
        double avgResponseTime = ((double) totalResponseTime.get()) / count;
        System.out.println("Time Passed: " + timePassedSeconds + "s, Query Executed: " + count + ", QPS: " + count / timePassedSeconds + ", Avg Response Time: " + avgResponseTime + "ms");
    }
}
Also used : CloseableHttpClient(org.apache.http.impl.client.CloseableHttpClient) HttpPost(org.apache.http.client.methods.HttpPost) IOException(java.io.IOException) StringEntity(org.apache.http.entity.StringEntity) AtomicLong(java.util.concurrent.atomic.AtomicLong) Random(java.util.Random) AtomicInteger(java.util.concurrent.atomic.AtomicInteger) ExecutorService(java.util.concurrent.ExecutorService) CloseableHttpResponse(org.apache.http.client.methods.CloseableHttpResponse) BufferedReader(java.io.BufferedReader) FileReader(java.io.FileReader)

Aggregations

StringEntity (org.apache.http.entity.StringEntity)458 HttpPost (org.apache.http.client.methods.HttpPost)251 HttpResponse (org.apache.http.HttpResponse)149 CloseableHttpResponse (org.apache.http.client.methods.CloseableHttpResponse)141 Test (org.junit.Test)105 HttpPut (org.apache.http.client.methods.HttpPut)94 ObjectNode (com.fasterxml.jackson.databind.node.ObjectNode)88 IOException (java.io.IOException)85 CloseableHttpClient (org.apache.http.impl.client.CloseableHttpClient)68 HttpEntity (org.apache.http.HttpEntity)61 JsonNode (com.fasterxml.jackson.databind.JsonNode)54 Deployment (org.activiti.engine.test.Deployment)50 TestHttpClient (io.undertow.testutils.TestHttpClient)30 ProcessInstance (org.activiti.engine.runtime.ProcessInstance)27 StatusLine (org.apache.http.StatusLine)27 HttpGet (org.apache.http.client.methods.HttpGet)27 Gson (com.google.gson.Gson)24 UnsupportedEncodingException (java.io.UnsupportedEncodingException)24 ProtocolVersion (org.apache.http.ProtocolVersion)24 BasicHttpResponse (org.apache.http.message.BasicHttpResponse)23