Search in sources :

Example 21 with UrlEncodedFormEntity

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);
        }
    }
}
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 22 with UrlEncodedFormEntity

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;
}
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 23 with UrlEncodedFormEntity

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) {
            }
        }
    }
}
Also used : BasicHttpContext(org.apache.http.protocol.BasicHttpContext) GZIPInputStream(java.util.zip.GZIPInputStream) StringEntity(org.apache.http.entity.StringEntity) MultipartEntity(org.apache.http.entity.mime.MultipartEntity) BasicNameValuePair(org.apache.http.message.BasicNameValuePair) AuthenticationHandler(org.apache.http.client.AuthenticationHandler) FileBody(org.apache.http.entity.mime.content.FileBody) GZIPInputStream(java.util.zip.GZIPInputStream) BasicHttpContext(org.apache.http.protocol.BasicHttpContext) HttpContext(org.apache.http.protocol.HttpContext) UrlEncodedFormEntity(org.apache.http.client.entity.UrlEncodedFormEntity)

Example 24 with UrlEncodedFormEntity

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;
}
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 25 with UrlEncodedFormEntity

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());
}
Also used : HttpPost(org.apache.http.client.methods.HttpPost) BasicNameValuePair(org.apache.http.message.BasicNameValuePair) CloseableHttpResponse(org.apache.http.client.methods.CloseableHttpResponse) UrlEncodedFormEntity(org.apache.http.client.entity.UrlEncodedFormEntity) BasicStatusLine(org.apache.http.message.BasicStatusLine) Test(org.junit.Test)

Aggregations

UrlEncodedFormEntity (org.apache.http.client.entity.UrlEncodedFormEntity)127 BasicNameValuePair (org.apache.http.message.BasicNameValuePair)105 HttpPost (org.apache.http.client.methods.HttpPost)99 NameValuePair (org.apache.http.NameValuePair)94 ArrayList (java.util.ArrayList)91 HttpResponse (org.apache.http.HttpResponse)71 IOException (java.io.IOException)45 HttpEntity (org.apache.http.HttpEntity)39 DefaultHttpClient (org.apache.http.impl.client.DefaultHttpClient)30 ClientProtocolException (org.apache.http.client.ClientProtocolException)27 UnsupportedEncodingException (java.io.UnsupportedEncodingException)23 Test (org.junit.Test)20 HttpClient (org.apache.http.client.HttpClient)19 HttpGet (org.apache.http.client.methods.HttpGet)19 JSONObject (org.json.JSONObject)17 Map (java.util.Map)16 TestHttpClient (io.undertow.testutils.TestHttpClient)14 Header (org.apache.http.Header)13 CloseableHttpResponse (org.apache.http.client.methods.CloseableHttpResponse)13 HashMap (java.util.HashMap)12