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