Search in sources :

Example 1 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 2 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 3 with HttpPost

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

the class EntityProcessor method process.

/**
	 * <p>Accepts the {@link InvocationContext} of an {@link HttpEntityEnclosingRequest} and inserts 
	 * <b>the</b> request parameter which is annotated with @{@link Entity} into its body.</p>
	 * 
	 * <p><b>Note</b> that it makes no sense to scope multiple entities within the same entity enclosing 
	 * request (HTTP/1.1 <a href="http://www.w3.org/Protocols/rfc2616/rfc2616-sec9.html">RFC-2616</a>). 
	 * This processor fails for the following scenarios:</p>
	 * 
	 * <ul>
	 * 	<li><b>No entity</b> was found in the endpoint method definition.</li>
	 * 	<li><b>Multiple entities</b> were found in the endpoint method definition.</li>
	 * 	<li>The annotated entity <b>failed to be resolved</b> to a matching {@link HttpEntity}.</li>
	 * </ul>
	 * 
	 * <p>Parameter types are resolved to their {@link HttpEntity} as specified in 
	 * {@link Entities#resolve(Object)}. If an attached @{@link Serialize} is discovered, the entity 
	 * will be serialized using the specified serializer before translation to an {@link HttpEntity}.</p>
	 * 
	 * <p>See {@link AbstractRequestProcessor#process(InvocationContext, HttpRequestBase)}.</p>
	 *
	 * @param context
	 * 			the {@link InvocationContext} which is used to retrieve the entity
	 * <br><br>
	 * @param request
	 * 			an instance of {@link HttpEntityEnclosingRequestBase} which allows the inclusion of an 
	 * 			{@link HttpEntity} in its body
	 * <br><br>
 	 * @return the same instance of {@link HttpRequestBase} which was given for processing entities 
	 * <br><br>
	 * @throws RequestProcessorException
	 * 			if an {@link HttpEntityEnclosingRequestBase} was discovered and yet the entity failed to 
	 * 			be resolved and inserted into the request body
	 * <br><br>
	 * @since 1.3.0
	 */
//welcomes a ClassCastException on misuse of @Serialize(Custom.class)
@Override
//welcomes a ClassCastException on misuse of @Serialize(Custom.class)
@SuppressWarnings("unchecked")
protected HttpRequestBase process(InvocationContext context, HttpRequestBase request) {
    try {
        if (request instanceof HttpEntityEnclosingRequestBase) {
            List<Entry<Entity, Object>> entities = Metadata.onParams(Entity.class, context);
            if (entities.isEmpty()) {
                throw new MissingEntityException(context);
            }
            if (entities.size() > 1) {
                throw new MultipleEntityException(context);
            }
            Object entity = entities.get(0).getValue();
            Serialize metadata = (metadata = context.getRequest().getAnnotation(Serialize.class)) == null ? context.getEndpoint().getAnnotation(Serialize.class) : metadata;
            if (metadata != null && !isDetached(context, Serialize.class)) {
                //no restrictions on custom serializer types with @Serialize
                @SuppressWarnings("rawtypes") AbstractSerializer serializer = (metadata.value() == UNDEFINED) ? Serializers.resolve(metadata.type()) : Serializers.resolve(metadata.value());
                entity = serializer.run(context, entity);
            }
            HttpEntity httpEntity = Entities.resolve(entity);
            ((HttpEntityEnclosingRequestBase) request).setHeader(HttpHeaders.CONTENT_TYPE, ContentType.getOrDefault(httpEntity).getMimeType());
            ((HttpEntityEnclosingRequestBase) request).setEntity(httpEntity);
        }
    } catch (MissingEntityException mee) {
        if (!(request instanceof HttpPost)) {
            //allow leeway for POST requests
            StringBuilder errorContext = new StringBuilder("It is imperative that this request encloses an entity.").append(" Identify exactly one entity by annotating an argument with @").append(Entity.class.getSimpleName());
            throw new RequestProcessorException(errorContext.toString(), mee);
        }
    } catch (MultipleEntityException mee) {
        //violates HTTP 1.1 specification, be more verbose 
        StringBuilder errorContext = new StringBuilder("This request is only able to enclose exactly one entity.").append(" Remove all @").append(Entity.class.getSimpleName()).append(" annotations except for a single entity which is identified by this URI. ");
        throw new RequestProcessorException(errorContext.toString(), mee);
    } catch (EntityResolutionFailedException erfe) {
        //violates HTTP 1.1 specification, be more verbose
        StringBuilder errorContext = new StringBuilder("This request cannot proceed without an enclosing entity.").append(" Ensure that the entity which is annotated with ").append(Entity.class.getSimpleName()).append(" complies with the supported types as documented in ").append(RequestUtils.class.getName()).append("#resolveHttpEntity(Object)");
        throw new RequestProcessorException(errorContext.toString(), erfe);
    } catch (Exception e) {
        throw new RequestProcessorException(context, getClass(), e);
    }
    return request;
}
Also used : HttpPost(org.apache.http.client.methods.HttpPost) HttpEntity(org.apache.http.HttpEntity) Entity(com.lonepulse.robozombie.annotation.Entity) HttpEntityEnclosingRequestBase(org.apache.http.client.methods.HttpEntityEnclosingRequestBase) Serialize(com.lonepulse.robozombie.annotation.Serialize) HttpEntity(org.apache.http.HttpEntity) EntityResolutionFailedException(com.lonepulse.robozombie.util.EntityResolutionFailedException) EntityResolutionFailedException(com.lonepulse.robozombie.util.EntityResolutionFailedException) Entry(java.util.Map.Entry)

Example 4 with HttpPost

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

the class AbstractAjaxCallback method httpPost.

private void httpPost(String url, Map<String, Object> params, AjaxStatus status) throws ClientProtocolException, IOException {
    AQUtility.debug("post", url);
    HttpEntityEnclosingRequestBase req = new HttpPost(url);
    httpEntity(url, req, params, status);
}
Also used : HttpPost(org.apache.http.client.methods.HttpPost) HttpEntityEnclosingRequestBase(org.apache.http.client.methods.HttpEntityEnclosingRequestBase)

Example 5 with HttpPost

use of org.apache.http.client.methods.HttpPost in project openhab1-addons by openhab.

the class StreamClientImpl method createHttpRequest.

protected HttpUriRequest createHttpRequest(UpnpMessage upnpMessage, UpnpRequest upnpRequestOperation) throws MethodNotSupportedException {
    switch(upnpRequestOperation.getMethod()) {
        case GET:
            return new HttpGet(upnpRequestOperation.getURI());
        case SUBSCRIBE:
            return new HttpGet(upnpRequestOperation.getURI()) {

                @Override
                public String getMethod() {
                    return UpnpRequest.Method.SUBSCRIBE.getHttpName();
                }
            };
        case UNSUBSCRIBE:
            return new HttpGet(upnpRequestOperation.getURI()) {

                @Override
                public String getMethod() {
                    return UpnpRequest.Method.UNSUBSCRIBE.getHttpName();
                }
            };
        case POST:
            HttpEntityEnclosingRequest post = new HttpPost(upnpRequestOperation.getURI());
            post.setEntity(createHttpRequestEntity(upnpMessage));
            // Fantastic API
            return (HttpUriRequest) post;
        case NOTIFY:
            HttpEntityEnclosingRequest notify = new HttpPost(upnpRequestOperation.getURI()) {

                @Override
                public String getMethod() {
                    return UpnpRequest.Method.NOTIFY.getHttpName();
                }
            };
            notify.setEntity(createHttpRequestEntity(upnpMessage));
            // Fantastic API
            return (HttpUriRequest) notify;
        default:
            throw new MethodNotSupportedException(upnpRequestOperation.getHttpMethodName());
    }
}
Also used : HttpUriRequest(org.apache.http.client.methods.HttpUriRequest) HttpPost(org.apache.http.client.methods.HttpPost) HttpGet(org.apache.http.client.methods.HttpGet) HttpEntityEnclosingRequest(org.apache.http.HttpEntityEnclosingRequest) MethodNotSupportedException(org.apache.http.MethodNotSupportedException)

Aggregations

HttpPost (org.apache.http.client.methods.HttpPost)696 HttpResponse (org.apache.http.HttpResponse)287 StringEntity (org.apache.http.entity.StringEntity)273 IOException (java.io.IOException)193 Test (org.junit.Test)179 CloseableHttpResponse (org.apache.http.client.methods.CloseableHttpResponse)167 UrlEncodedFormEntity (org.apache.http.client.entity.UrlEncodedFormEntity)123 CloseableHttpClient (org.apache.http.impl.client.CloseableHttpClient)121 BasicNameValuePair (org.apache.http.message.BasicNameValuePair)115 HttpEntity (org.apache.http.HttpEntity)114 ArrayList (java.util.ArrayList)106 NameValuePair (org.apache.http.NameValuePair)100 HttpClient (org.apache.http.client.HttpClient)86 DefaultHttpClient (org.apache.http.impl.client.DefaultHttpClient)76 HttpGet (org.apache.http.client.methods.HttpGet)62 ClientProtocolException (org.apache.http.client.ClientProtocolException)56 TestHttpClient (io.undertow.testutils.TestHttpClient)54 ObjectNode (com.fasterxml.jackson.databind.node.ObjectNode)49 InputStream (java.io.InputStream)47 File (java.io.File)43