Search in sources :

Example 51 with HttpPost

use of org.apache.http.client.methods.HttpPost in project Talon-for-Twitter by klinker24.

the class TwitLongerHelper method postToTwitLonger.

/**
     * Posts the status to twitlonger
     * @return returns an object containing the shortened text and the id for the twitlonger url
     */
public TwitLongerStatus postToTwitLonger() {
    try {
        HttpClient client = new DefaultHttpClient();
        HttpPost post = new HttpPost(POST_URL);
        post.addHeader("X-API-KEY", TWITLONGER_API_KEY);
        post.addHeader("X-Auth-Service-Provider", SERVICE_PROVIDER);
        post.addHeader("X-Verify-Credentials-Authorization", getAuthrityHeader(twitter));
        List<NameValuePair> nvps = new ArrayList<NameValuePair>();
        nvps.add(new BasicNameValuePair("content", tweetText));
        if (replyToId != 0) {
            nvps.add(new BasicNameValuePair("reply_to_id", String.valueOf(replyToId)));
        } else if (replyToScreenname != null) {
            nvps.add(new BasicNameValuePair("reply_to_screen_name", replyToScreenname));
        }
        post.setEntity(new UrlEncodedFormEntity(nvps, HTTP.UTF_8));
        HttpResponse response = client.execute(post);
        BufferedReader rd = new BufferedReader(new InputStreamReader(response.getEntity().getContent()));
        String line;
        String content = "";
        String id = "";
        StringBuilder builder = new StringBuilder();
        while ((line = rd.readLine()) != null) {
            builder.append(line);
        }
        try {
            // there is only going to be one thing returned ever
            JSONObject jsonObject = new JSONObject(builder.toString());
            content = jsonObject.getString("tweet_content");
            id = jsonObject.getString("id");
        } catch (Exception e) {
            e.printStackTrace();
        }
        Log.v("talon_twitlonger", "content: " + content);
        Log.v("talon_twitlonger", "id: " + id);
        return new TwitLongerStatus(content, id);
    } catch (Exception e) {
        e.printStackTrace();
    }
    return null;
}
Also used : HttpPost(org.apache.http.client.methods.HttpPost) BasicNameValuePair(org.apache.http.message.BasicNameValuePair) NameValuePair(org.apache.http.NameValuePair) InputStreamReader(java.io.InputStreamReader) ArrayList(java.util.ArrayList) HttpResponse(org.apache.http.HttpResponse) UrlEncodedFormEntity(org.apache.http.client.entity.UrlEncodedFormEntity) DefaultHttpClient(org.apache.http.impl.client.DefaultHttpClient) JSONObject(org.json.JSONObject) DefaultHttpClient(org.apache.http.impl.client.DefaultHttpClient) HttpClient(org.apache.http.client.HttpClient) BasicNameValuePair(org.apache.http.message.BasicNameValuePair) BufferedReader(java.io.BufferedReader)

Example 52 with HttpPost

use of org.apache.http.client.methods.HttpPost in project Talon-for-Twitter by klinker24.

the class TwitPicHelper method uploadToTwitPic.

private TwitPicStatus uploadToTwitPic() {
    try {
        HttpClient client = new DefaultHttpClient();
        HttpPost post = new HttpPost(POST_URL);
        post.addHeader("X-Auth-Service-Provider", SERVICE_PROVIDER);
        post.addHeader("X-Verify-Credentials-Authorization", getAuthrityHeader(twitter));
        if (file == null) {
            // only the input stream was sent, so we need to convert it to a file
            Log.v("talon_twitpic", "converting to file from input stream");
            String filePath = saveStreamTemp(stream);
            file = new File(filePath);
        } else {
            Log.v("talon_twitpic", "already have the file, going right to send it");
        }
        MultipartEntity entity = new MultipartEntity(HttpMultipartMode.BROWSER_COMPATIBLE);
        entity.addPart("key", new StringBody(TWITPIC_API_KEY));
        entity.addPart("media", new FileBody(file));
        entity.addPart("message", new StringBody(message));
        Log.v("talon_twitpic", "uploading now");
        post.setEntity(entity);
        HttpResponse response = client.execute(post);
        BufferedReader rd = new BufferedReader(new InputStreamReader(response.getEntity().getContent()));
        String line;
        String url = "";
        StringBuilder builder = new StringBuilder();
        while ((line = rd.readLine()) != null) {
            Log.v("talon_twitpic", line);
            builder.append(line);
        }
        try {
            // there is only going to be one thing returned ever
            JSONObject jsonObject = new JSONObject(builder.toString());
            url = jsonObject.getString("url");
        } catch (Exception e) {
            e.printStackTrace();
        }
        Log.v("talon_twitpic", "url: " + url);
        Log.v("talon_twitpic", "message: " + message);
        return new TwitPicStatus(message, url);
    } catch (Exception e) {
        e.printStackTrace();
    }
    return null;
}
Also used : HttpPost(org.apache.http.client.methods.HttpPost) FileBody(org.apache.http.entity.mime.content.FileBody) InputStreamReader(java.io.InputStreamReader) HttpResponse(org.apache.http.HttpResponse) DefaultHttpClient(org.apache.http.impl.client.DefaultHttpClient) IOException(java.io.IOException) FileNotFoundException(java.io.FileNotFoundException) JSONObject(org.json.JSONObject) MultipartEntity(org.apache.http.entity.mime.MultipartEntity) StringBody(org.apache.http.entity.mime.content.StringBody) DefaultHttpClient(org.apache.http.impl.client.DefaultHttpClient) HttpClient(org.apache.http.client.HttpClient) BufferedReader(java.io.BufferedReader) File(java.io.File)

Example 53 with HttpPost

use of org.apache.http.client.methods.HttpPost in project android-volley by mcxiaoke.

the class HttpClientStackTest method createPostRequestWithBody.

@Test
public void createPostRequestWithBody() throws Exception {
    TestRequest.PostWithBody request = new TestRequest.PostWithBody();
    assertEquals(request.getMethod(), Method.POST);
    HttpUriRequest httpRequest = HttpClientStack.createHttpRequest(request, null);
    assertTrue(httpRequest instanceof HttpPost);
}
Also used : HttpUriRequest(org.apache.http.client.methods.HttpUriRequest) HttpPost(org.apache.http.client.methods.HttpPost) TestRequest(com.android.volley.mock.TestRequest) Test(org.junit.Test)

Example 54 with HttpPost

use of org.apache.http.client.methods.HttpPost 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 55 with HttpPost

use of org.apache.http.client.methods.HttpPost 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

HttpPost (org.apache.http.client.methods.HttpPost)531 HttpResponse (org.apache.http.HttpResponse)238 StringEntity (org.apache.http.entity.StringEntity)220 Test (org.junit.Test)153 IOException (java.io.IOException)143 CloseableHttpResponse (org.apache.http.client.methods.CloseableHttpResponse)107 UrlEncodedFormEntity (org.apache.http.client.entity.UrlEncodedFormEntity)99 BasicNameValuePair (org.apache.http.message.BasicNameValuePair)90 ArrayList (java.util.ArrayList)86 NameValuePair (org.apache.http.NameValuePair)84 HttpEntity (org.apache.http.HttpEntity)83 DefaultHttpClient (org.apache.http.impl.client.DefaultHttpClient)68 HttpClient (org.apache.http.client.HttpClient)64 CloseableHttpClient (org.apache.http.impl.client.CloseableHttpClient)63 HttpGet (org.apache.http.client.methods.HttpGet)55 TestHttpClient (io.undertow.testutils.TestHttpClient)54 ObjectNode (com.fasterxml.jackson.databind.node.ObjectNode)49 ClientProtocolException (org.apache.http.client.ClientProtocolException)49 JsonNode (com.fasterxml.jackson.databind.JsonNode)39 InputStream (java.io.InputStream)29