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);
}
}
}
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;
}
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;
}
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);
}
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());
}
}
Aggregations