use of org.apache.http.client.entity.UrlEncodedFormEntity 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.entity.UrlEncodedFormEntity 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.entity.UrlEncodedFormEntity in project FBReaderJ by geometer.
the class ZLNetworkManager method perform.
void perform(ZLNetworkRequest request, BearerAuthenticator authenticator, int socketTimeout, int connectionTimeout) throws ZLNetworkException {
boolean success = false;
DefaultHttpClient httpClient = null;
HttpEntity entity = null;
try {
final HttpContext httpContext = new BasicHttpContext();
httpContext.setAttribute(ClientContext.COOKIE_STORE, CookieStore);
request.doBefore();
final HttpParams params = new BasicHttpParams();
HttpConnectionParams.setSoTimeout(params, socketTimeout);
HttpConnectionParams.setConnectionTimeout(params, connectionTimeout);
httpClient = new DefaultHttpClient(params) {
protected AuthenticationHandler createTargetAuthenticationHandler() {
final AuthenticationHandler base = super.createTargetAuthenticationHandler();
return new AuthenticationHandler() {
public Map<String, Header> getChallenges(HttpResponse response, HttpContext context) throws MalformedChallengeException {
return base.getChallenges(response, context);
}
public boolean isAuthenticationRequested(HttpResponse response, HttpContext context) {
return base.isAuthenticationRequested(response, context);
}
public AuthScheme selectScheme(Map<String, Header> challenges, HttpResponse response, HttpContext context) throws AuthenticationException {
try {
return base.selectScheme(challenges, response, context);
} catch (AuthenticationException e) {
final Header bearerHeader = challenges.get("bearer");
if (bearerHeader != null) {
String realm = null;
for (HeaderElement elt : bearerHeader.getElements()) {
final String name = elt.getName();
if (name == null) {
continue;
}
if ("realm".equals(name) || name.endsWith(" realm")) {
realm = elt.getValue();
break;
}
}
throw new BearerAuthenticationException(realm, response.getEntity());
}
throw e;
}
}
};
}
};
final HttpRequestBase httpRequest;
if (request instanceof ZLNetworkRequest.Get) {
httpRequest = new HttpGet(request.URL);
} else if (request instanceof ZLNetworkRequest.PostWithBody) {
httpRequest = new HttpPost(request.URL);
((HttpPost) httpRequest).setEntity(new StringEntity(((ZLNetworkRequest.PostWithBody) request).Body, "utf-8"));
/*
httpConnection.setRequestProperty(
"Content-Length",
Integer.toString(request.Body.getBytes().length)
);
*/
} else if (request instanceof ZLNetworkRequest.PostWithMap) {
final Map<String, String> parameters = ((ZLNetworkRequest.PostWithMap) request).PostParameters;
httpRequest = new HttpPost(request.URL);
final List<BasicNameValuePair> list = new ArrayList<BasicNameValuePair>(parameters.size());
for (Map.Entry<String, String> entry : parameters.entrySet()) {
list.add(new BasicNameValuePair(entry.getKey(), entry.getValue()));
}
((HttpPost) httpRequest).setEntity(new UrlEncodedFormEntity(list, "utf-8"));
} else if (request instanceof ZLNetworkRequest.FileUpload) {
final ZLNetworkRequest.FileUpload uploadRequest = (ZLNetworkRequest.FileUpload) request;
final File file = ((ZLNetworkRequest.FileUpload) request).File;
httpRequest = new HttpPost(request.URL);
final MultipartEntity data = new MultipartEntity(HttpMultipartMode.BROWSER_COMPATIBLE, null, Charset.forName("utf-8"));
data.addPart("file", new FileBody(uploadRequest.File));
((HttpPost) httpRequest).setEntity(data);
} else {
throw new ZLNetworkException("Unknown request type");
}
httpRequest.setHeader("User-Agent", ZLNetworkUtil.getUserAgent());
if (!request.isQuiet()) {
httpRequest.setHeader("X-Accept-Auto-Login", "True");
}
httpRequest.setHeader("Accept-Encoding", "gzip");
httpRequest.setHeader("Accept-Language", ZLResource.getLanguage());
for (Map.Entry<String, String> header : request.Headers.entrySet()) {
httpRequest.setHeader(header.getKey(), header.getValue());
}
httpClient.setCredentialsProvider(new MyCredentialsProvider(httpRequest, request.isQuiet()));
final HttpResponse response = execute(httpClient, httpRequest, httpContext, authenticator);
entity = response.getEntity();
if (response.getStatusLine().getStatusCode() == HttpURLConnection.HTTP_UNAUTHORIZED) {
final AuthState state = (AuthState) httpContext.getAttribute(ClientContext.TARGET_AUTH_STATE);
if (state != null) {
final AuthScopeKey key = new AuthScopeKey(state.getAuthScope());
if (myCredentialsCreator.removeCredentials(key)) {
entity = null;
}
}
}
final int responseCode = response.getStatusLine().getStatusCode();
InputStream stream = null;
if (entity != null && (responseCode == HttpURLConnection.HTTP_OK || responseCode == HttpURLConnection.HTTP_PARTIAL)) {
stream = entity.getContent();
}
if (stream != null) {
try {
final Header encoding = entity.getContentEncoding();
if (encoding != null && "gzip".equalsIgnoreCase(encoding.getValue())) {
stream = new GZIPInputStream(stream);
}
request.handleStream(stream, (int) entity.getContentLength());
} finally {
stream.close();
}
success = true;
} else {
if (responseCode == HttpURLConnection.HTTP_UNAUTHORIZED) {
throw new ZLNetworkAuthenticationException();
} else {
throw new ZLNetworkException(response.getStatusLine().toString());
}
}
} catch (ZLNetworkException e) {
throw e;
} catch (IOException e) {
e.printStackTrace();
final String code;
if (e instanceof UnknownHostException) {
code = ZLNetworkException.ERROR_RESOLVE_HOST;
} else {
code = ZLNetworkException.ERROR_CONNECT_TO_HOST;
}
throw ZLNetworkException.forCode(code, ZLNetworkUtil.hostFromUrl(request.URL), e);
} catch (Exception e) {
e.printStackTrace();
throw new ZLNetworkException(e.getMessage(), e);
} finally {
request.doAfter(success);
if (httpClient != null) {
httpClient.getConnectionManager().shutdown();
}
if (entity != null) {
try {
entity.consumeContent();
} catch (IOException e) {
}
}
}
}
use of org.apache.http.client.entity.UrlEncodedFormEntity 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;
}
use of org.apache.http.client.entity.UrlEncodedFormEntity in project gocd by gocd.
the class HttpServiceTest method shouldSetTheAcceptHeaderWhilePostingProperties.
@Test
public void shouldSetTheAcceptHeaderWhilePostingProperties() throws Exception {
HttpPost post = mock(HttpPost.class);
when(httpClientFactory.createPost("url")).thenReturn(post);
CloseableHttpResponse response = mock(CloseableHttpResponse.class);
when(response.getStatusLine()).thenReturn(new BasicStatusLine(HttpVersion.HTTP_1_1, 200, "OK"));
when(httpClient.execute(post)).thenReturn(response);
ArgumentCaptor<UrlEncodedFormEntity> entityCaptor = ArgumentCaptor.forClass(UrlEncodedFormEntity.class);
service.postProperty("url", "value");
verify(post).setHeader("Confirm", "true");
verify(post).setEntity(entityCaptor.capture());
UrlEncodedFormEntity expected = new UrlEncodedFormEntity(Arrays.asList(new BasicNameValuePair("value", "value")));
UrlEncodedFormEntity actual = entityCaptor.getValue();
assertEquals(IOUtils.toString(expected.getContent()), IOUtils.toString(actual.getContent()));
assertEquals(expected.getContentLength(), expected.getContentLength());
assertEquals(expected.getContentType(), expected.getContentType());
assertEquals(expected.getContentEncoding(), expected.getContentEncoding());
assertEquals(expected.isChunked(), expected.isChunked());
}
Aggregations