Search in sources :

Example 91 with HttpPost

use of org.apache.http.client.methods.HttpPost in project Android-Error-Reporter by tomquist.

the class ExceptionReportService method sendReport.

private void sendReport(Intent intent) throws UnsupportedEncodingException, NameNotFoundException {
    Log.v(TAG, "Got request to report error: " + intent.toString());
    Uri server = getTargetUrl();
    boolean isManualReport = intent.getBooleanExtra(EXTRA_MANUAL_REPORT, false);
    boolean isReportOnFroyo = isReportOnFroyo();
    boolean isFroyoOrAbove = isFroyoOrAbove();
    if (isFroyoOrAbove && !isManualReport && !isReportOnFroyo) {
        // We don't send automatic reports on froyo or above
        Log.d(TAG, "Don't send automatic report on froyo");
        return;
    }
    Set<String> fieldsToSend = getFieldsToSend();
    String stacktrace = intent.getStringExtra(EXTRA_STACK_TRACE);
    String exception = intent.getStringExtra(EXTRA_EXCEPTION_CLASS);
    String message = intent.getStringExtra(EXTRA_MESSAGE);
    long availableMemory = intent.getLongExtra(EXTRA_AVAILABLE_MEMORY, -1l);
    long totalMemory = intent.getLongExtra(EXTRA_TOTAL_MEMORY, -1l);
    String dateTime = intent.getStringExtra(EXTRA_EXCEPTION_TIME);
    String threadName = intent.getStringExtra(EXTRA_THREAD_NAME);
    String extraMessage = intent.getStringExtra(EXTRA_EXTRA_MESSAGE);
    List<NameValuePair> params = new ArrayList<NameValuePair>();
    addNameValuePair(params, fieldsToSend, "exStackTrace", stacktrace);
    addNameValuePair(params, fieldsToSend, "exClass", exception);
    addNameValuePair(params, fieldsToSend, "exDateTime", dateTime);
    addNameValuePair(params, fieldsToSend, "exMessage", message);
    addNameValuePair(params, fieldsToSend, "exThreadName", threadName);
    if (extraMessage != null)
        addNameValuePair(params, fieldsToSend, "extraMessage", extraMessage);
    if (availableMemory >= 0)
        addNameValuePair(params, fieldsToSend, "devAvailableMemory", availableMemory + "");
    if (totalMemory >= 0)
        addNameValuePair(params, fieldsToSend, "devTotalMemory", totalMemory + "");
    PackageManager pm = getPackageManager();
    try {
        PackageInfo packageInfo = pm.getPackageInfo(getPackageName(), 0);
        addNameValuePair(params, fieldsToSend, "appVersionCode", packageInfo.versionCode + "");
        addNameValuePair(params, fieldsToSend, "appVersionName", packageInfo.versionName);
        addNameValuePair(params, fieldsToSend, "appPackageName", packageInfo.packageName);
    } catch (NameNotFoundException e) {
    }
    addNameValuePair(params, fieldsToSend, "devModel", android.os.Build.MODEL);
    addNameValuePair(params, fieldsToSend, "devSdk", android.os.Build.VERSION.SDK);
    addNameValuePair(params, fieldsToSend, "devReleaseVersion", android.os.Build.VERSION.RELEASE);
    HttpClient httpClient = new DefaultHttpClient();
    HttpPost post = new HttpPost(server.toString());
    post.setEntity(new UrlEncodedFormEntity(params, HTTP.UTF_8));
    Log.d(TAG, "Created post request");
    try {
        httpClient.execute(post);
        Log.v(TAG, "Reported error: " + intent.toString());
    } catch (ClientProtocolException e) {
        // Ignore this kind of error
        Log.e(TAG, "Error while sending an error report", e);
    } catch (SSLException e) {
        Log.e(TAG, "Error while sending an error report", e);
    } catch (IOException e) {
        if (e instanceof SocketException && e.getMessage().contains("Permission denied")) {
            Log.e(TAG, "You don't have internet permission", e);
        } else {
            int maximumRetryCount = getMaximumRetryCount();
            int maximumExponent = getMaximumBackoffExponent();
            // Retry at a later point in time
            AlarmManager alarmMgr = (AlarmManager) getSystemService(ALARM_SERVICE);
            int exponent = intent.getIntExtra(EXTRA_CURRENT_RETRY_COUNT, 0);
            intent.putExtra(EXTRA_CURRENT_RETRY_COUNT, exponent + 1);
            PendingIntent operation = PendingIntent.getService(this, 0, intent, PendingIntent.FLAG_CANCEL_CURRENT);
            if (exponent >= maximumRetryCount) {
                // Discard error
                Log.w(TAG, "Error report reached the maximum retry count and will be discarded.\nStacktrace:\n" + stacktrace);
                return;
            }
            if (exponent > maximumExponent) {
                exponent = maximumExponent;
            }
            // backoff in ms
            long backoff = (1 << exponent) * 1000;
            alarmMgr.set(AlarmManager.ELAPSED_REALTIME, SystemClock.elapsedRealtime() + backoff, operation);
        }
    }
}
Also used : BasicNameValuePair(org.apache.http.message.BasicNameValuePair) NameValuePair(org.apache.http.NameValuePair) HttpPost(org.apache.http.client.methods.HttpPost) SocketException(java.net.SocketException) NameNotFoundException(android.content.pm.PackageManager.NameNotFoundException) PackageInfo(android.content.pm.PackageInfo) ArrayList(java.util.ArrayList) UrlEncodedFormEntity(org.apache.http.client.entity.UrlEncodedFormEntity) IOException(java.io.IOException) Uri(android.net.Uri) SSLException(javax.net.ssl.SSLException) DefaultHttpClient(org.apache.http.impl.client.DefaultHttpClient) ClientProtocolException(org.apache.http.client.ClientProtocolException) PackageManager(android.content.pm.PackageManager) DefaultHttpClient(org.apache.http.impl.client.DefaultHttpClient) HttpClient(org.apache.http.client.HttpClient) AlarmManager(android.app.AlarmManager) PendingIntent(android.app.PendingIntent)

Example 92 with HttpPost

use of org.apache.http.client.methods.HttpPost in project google-analytics-java by brsanthu.

the class GoogleAnalyticsThreadFactory method post.

@SuppressWarnings({ "rawtypes" })
public GoogleAnalyticsResponse post(GoogleAnalyticsRequest request) {
    GoogleAnalyticsResponse response = new GoogleAnalyticsResponse();
    if (!config.isEnabled()) {
        return response;
    }
    CloseableHttpResponse httpResponse = null;
    try {
        List<NameValuePair> postParms = new ArrayList<NameValuePair>();
        logger.debug("Processing " + request);
        //Process the parameters
        processParameters(request, postParms);
        //Process custom dimensions
        processCustomDimensionParameters(request, postParms);
        //Process custom metrics
        processCustomMetricParameters(request, postParms);
        logger.debug("Processed all parameters and sending the request " + postParms);
        HttpPost httpPost = new HttpPost(config.getUrl());
        httpPost.setEntity(new UrlEncodedFormEntity(postParms, UTF8));
        httpResponse = (CloseableHttpResponse) httpClient.execute(httpPost);
        response.setStatusCode(httpResponse.getStatusLine().getStatusCode());
        response.setPostedParms(postParms);
        EntityUtils.consumeQuietly(httpResponse.getEntity());
        if (config.isGatherStats()) {
            gatherStats(request);
        }
    } catch (Exception e) {
        if (e instanceof UnknownHostException) {
            logger.warn("Coudln't connect to Google Analytics. Internet may not be available. " + e.toString());
        } else {
            logger.warn("Exception while sending the Google Analytics tracker request " + request, e);
        }
    } finally {
        try {
            httpResponse.close();
        } catch (Exception e2) {
        //ignore
        }
    }
    return response;
}
Also used : BasicNameValuePair(org.apache.http.message.BasicNameValuePair) NameValuePair(org.apache.http.NameValuePair) HttpPost(org.apache.http.client.methods.HttpPost) UnknownHostException(java.net.UnknownHostException) CloseableHttpResponse(org.apache.http.client.methods.CloseableHttpResponse) ArrayList(java.util.ArrayList) UrlEncodedFormEntity(org.apache.http.client.entity.UrlEncodedFormEntity) IOException(java.io.IOException) UnknownHostException(java.net.UnknownHostException)

Example 93 with HttpPost

use of org.apache.http.client.methods.HttpPost in project android-sqrl by geir54.

the class MainActivity method web_post.

// Send signature and pubkey to server
private boolean web_post(String URL, String message, String signature, String publicKey) {
    HttpClient httpclient = new DefaultHttpClient();
    HttpPost httppost = new HttpPost(URL);
    try {
        // Add data to post
        List<NameValuePair> nameValuePairs = new ArrayList<NameValuePair>(2);
        nameValuePairs.add(new BasicNameValuePair("message", message));
        nameValuePairs.add(new BasicNameValuePair("signature", signature));
        nameValuePairs.add(new BasicNameValuePair("publicKey", publicKey));
        httppost.setEntity(new UrlEncodedFormEntity(nameValuePairs));
        // Execute HTTP Post Request
        HttpResponse response = httpclient.execute(httppost);
        int status = response.getStatusLine().getStatusCode();
        if (status == HttpStatus.SC_OK) {
            ByteArrayOutputStream ostream = new ByteArrayOutputStream();
            response.getEntity().writeTo(ostream);
            String out = ostream.toString();
            Log.v("web", out);
            // See if the page returned "Verified"
            if (out.contains("Verified")) {
                // return true if verified
                return true;
            }
        } else {
            Log.v("web", "Connection not ok");
        }
    } catch (ClientProtocolException e) {
        Log.e("web", "error");
    } catch (IOException e) {
        Log.e("web", "error");
    }
    // Return false if query did not return verification
    return false;
}
Also used : HttpPost(org.apache.http.client.methods.HttpPost) BasicNameValuePair(org.apache.http.message.BasicNameValuePair) NameValuePair(org.apache.http.NameValuePair) ArrayList(java.util.ArrayList) HttpResponse(org.apache.http.HttpResponse) UrlEncodedFormEntity(org.apache.http.client.entity.UrlEncodedFormEntity) ByteArrayOutputStream(java.io.ByteArrayOutputStream) IOException(java.io.IOException) DefaultHttpClient(org.apache.http.impl.client.DefaultHttpClient) ClientProtocolException(org.apache.http.client.ClientProtocolException) DefaultHttpClient(org.apache.http.impl.client.DefaultHttpClient) HttpClient(org.apache.http.client.HttpClient) BasicNameValuePair(org.apache.http.message.BasicNameValuePair)

Example 94 with HttpPost

use of org.apache.http.client.methods.HttpPost in project gocd by gocd.

the class GoHttpClientHttpInvokerRequestExecutor method doExecuteRequest.

@Override
protected RemoteInvocationResult doExecuteRequest(HttpInvokerClientConfiguration config, ByteArrayOutputStream baos) throws Exception {
    HttpPost postMethod = new HttpPost(config.getServiceUrl());
    ByteArrayEntity entity = new ByteArrayEntity(baos.toByteArray());
    entity.setContentType(getContentType());
    postMethod.setEntity(entity);
    BasicHttpContext context = null;
    if (environment.useSslContext()) {
        context = new BasicHttpContext();
        context.setAttribute(HttpClientContext.USER_TOKEN, goAgentServerHttpClient.principal());
    }
    try (CloseableHttpResponse response = goAgentServerHttpClient.execute(postMethod, context)) {
        validateResponse(response);
        InputStream responseBody = getResponseBody(response);
        return readRemoteInvocationResult(responseBody, config.getCodebaseUrl());
    }
}
Also used : HttpPost(org.apache.http.client.methods.HttpPost) ByteArrayEntity(org.apache.http.entity.ByteArrayEntity) BasicHttpContext(org.apache.http.protocol.BasicHttpContext) GZIPInputStream(java.util.zip.GZIPInputStream) InputStream(java.io.InputStream) CloseableHttpResponse(org.apache.http.client.methods.CloseableHttpResponse)

Example 95 with HttpPost

use of org.apache.http.client.methods.HttpPost in project gitblit by gitblit.

the class FilestoreServletTest method testUpload.

@Test
public void testUpload() throws Exception {
    FileUtils.delete(filestore().getStorageFolder());
    filestore().clearFilestoreCache();
    RepositoryModel r = gitblit().getRepositoryModel(repoName);
    UserModel u = new UserModel("admin");
    u.canAdmin = true;
    //No upload limit
    settings().overrideSetting(Keys.filestore.maxUploadSize, FilestoreManager.UNDEFINED_SIZE);
    final BlobInfo blob = new BlobInfo(512 * FileUtils.KB);
    final String expectedUploadURL = GitBlitSuite.url + repoLfs + blob.hash;
    final String initialUploadURL = GitBlitSuite.url + repoLfs + "batch";
    HttpClient client = HttpClientBuilder.create().build();
    HttpPost request = new HttpPost(initialUploadURL);
    // add request header
    request.addHeader(HttpHeaders.ACCEPT, FilestoreServlet.GIT_LFS_META_MIME);
    request.addHeader(HttpHeaders.CONTENT_ENCODING, FilestoreServlet.GIT_LFS_META_MIME);
    String content = String.format("{%s:%s,%s:[{%s:%s,%s:%d}]}", "\"operation\"", "\"upload\"", "\"objects\"", "\"oid\"", "\"" + blob.hash + "\"", "\"size\"", blob.length);
    HttpEntity entity = new ByteArrayEntity(content.getBytes("UTF-8"));
    request.setEntity(entity);
    HttpResponse response = client.execute(request);
    String responseMessage = IOUtils.toString(response.getEntity().getContent(), "UTF-8");
    assertEquals(200, response.getStatusLine().getStatusCode());
    String expectedContent = String.format("{%s:[{%s:%s,%s:%d,%s:{%s:{%s:%s}}}]}", "\"objects\"", "\"oid\"", "\"" + blob.hash + "\"", "\"size\"", blob.length, "\"actions\"", "\"upload\"", "\"href\"", "\"" + expectedUploadURL + "\"");
    assertEquals(expectedContent, responseMessage);
    //Now try to upload the binary download
    HttpPut putRequest = new HttpPut(expectedUploadURL);
    putRequest.setEntity(new ByteArrayEntity(blob.blob));
    response = client.execute(putRequest);
    responseMessage = IOUtils.toString(response.getEntity().getContent(), "UTF-8");
    assertEquals(200, response.getStatusLine().getStatusCode());
    //Confirm behind the scenes that it is available
    ByteArrayOutputStream savedBlob = new ByteArrayOutputStream();
    assertEquals(Status.Available, filestore().downloadBlob(blob.hash, u, r, savedBlob));
    assertArrayEquals(blob.blob, savedBlob.toByteArray());
}
Also used : UserModel(com.gitblit.models.UserModel) HttpPost(org.apache.http.client.methods.HttpPost) HttpEntity(org.apache.http.HttpEntity) ByteArrayEntity(org.apache.http.entity.ByteArrayEntity) HttpClient(org.apache.http.client.HttpClient) HttpResponse(org.apache.http.HttpResponse) RepositoryModel(com.gitblit.models.RepositoryModel) ByteArrayOutputStream(java.io.ByteArrayOutputStream) HttpPut(org.apache.http.client.methods.HttpPut) Test(org.junit.Test)

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