Search in sources :

Example 46 with NameValuePair

use of org.apache.http.NameValuePair 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 47 with NameValuePair

use of org.apache.http.NameValuePair 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 48 with NameValuePair

use of org.apache.http.NameValuePair in project androidquery by androidquery.

the class AQueryAsyncTest method testAjaxPostRaw.

public void testAjaxPostRaw() throws UnsupportedEncodingException {
    String url = "http://www.androidquery.com/p/doNothing";
    List<NameValuePair> pairs = new ArrayList<NameValuePair>();
    pairs.add(new BasicNameValuePair("q", "androidquery"));
    HttpEntity entity = new UrlEncodedFormEntity(pairs, "UTF-8");
    Map<String, Object> params = new HashMap<String, Object>();
    params.put(AQuery.POST_ENTITY, entity);
    aq.ajax(url, params, JSONObject.class, new AjaxCallback<JSONObject>() {

        @Override
        public void callback(String url, JSONObject jo, AjaxStatus status) {
            done(url, jo, status);
        }
    });
    waitAsync();
    JSONObject jo = (JSONObject) result;
    assertNotNull(jo);
    assertNotNull(jo.opt("params"));
    assertEquals("POST", jo.optString("method"));
}
Also used : NameValuePair(org.apache.http.NameValuePair) BasicNameValuePair(org.apache.http.message.BasicNameValuePair) HttpEntity(org.apache.http.HttpEntity) HashMap(java.util.HashMap) LinkedHashMap(java.util.LinkedHashMap) ArrayList(java.util.ArrayList) UrlEncodedFormEntity(org.apache.http.client.entity.UrlEncodedFormEntity) JSONObject(org.json.JSONObject) BasicNameValuePair(org.apache.http.message.BasicNameValuePair) JsonObject(com.google.gson.JsonObject) JSONObject(org.json.JSONObject) AjaxStatus(com.androidquery.callback.AjaxStatus)

Example 49 with NameValuePair

use of org.apache.http.NameValuePair in project androidquery by androidquery.

the class AjaxLoadingActivity method async_post_entity.

/*
	public void async_post2(){
		
        String url = "your url";
		
        //get your byte array or file
        byte[] data = new byte[1000];
        
		Map<String, Object> params = new HashMap<String, Object>();
		
		//put your post params
		params.put("paramName", data);
		
		AjaxCallback<byte[]> cb = new AjaxCallback<byte[]>() {

            @Override
            public void callback(String url, byte[] data, AjaxStatus status) {
               
            	System.out.println(data);
            	System.out.println(status.getCode() + ":" + status.getError());
                
            	
            }
        };
        
        cb.url(url).type(byte[].class);
        
        //set Content-Length header
        cb.params(params).header("Content-Length", Integer.toString(data.length));
		cb.async(this);
		
	}
	*/
public void async_post_entity() throws UnsupportedEncodingException {
    String url = "http://search.twitter.com/search.json";
    List<NameValuePair> pairs = new ArrayList<NameValuePair>();
    pairs.add(new BasicNameValuePair("q", "androidquery"));
    HttpEntity entity = new UrlEncodedFormEntity(pairs, "UTF-8");
    Map<String, Object> params = new HashMap<String, Object>();
    params.put(AQuery.POST_ENTITY, entity);
    aq.progress(R.id.progress).ajax(url, params, JSONObject.class, new AjaxCallback<JSONObject>() {

        @Override
        public void callback(String url, JSONObject json, AjaxStatus status) {
            showResult(json, status);
        }
    });
}
Also used : BasicNameValuePair(org.apache.http.message.BasicNameValuePair) NameValuePair(org.apache.http.NameValuePair) HttpEntity(org.apache.http.HttpEntity) HashMap(java.util.HashMap) LinkedHashMap(java.util.LinkedHashMap) ArrayList(java.util.ArrayList) UrlEncodedFormEntity(org.apache.http.client.entity.UrlEncodedFormEntity) JSONObject(org.json.JSONObject) BasicNameValuePair(org.apache.http.message.BasicNameValuePair) JSONObject(org.json.JSONObject) AjaxStatus(com.androidquery.callback.AjaxStatus)

Example 50 with NameValuePair

use of org.apache.http.NameValuePair in project android-instagram by markchang.

the class ImageListActivity method postComment.

public void postComment(String comment, InstagramImage image, String username) {
    List<NameValuePair> postParams = new ArrayList<NameValuePair>();
    postParams.add(new BasicNameValuePair("comment_text", comment));
    String jsonResponse = Utils.doRestulPut(httpClient, Utils.createCommentUrl(image.pk), postParams, this);
    if (jsonResponse != null) {
        image.comment_list.add(new Comment(username, comment));
        Toast.makeText(this, "Comment successful", Toast.LENGTH_SHORT).show();
        adapter.notifyDataSetChanged();
    } else {
        Toast.makeText(this, "Comment failed", Toast.LENGTH_SHORT).show();
    }
}
Also used : BasicNameValuePair(org.apache.http.message.BasicNameValuePair) NameValuePair(org.apache.http.NameValuePair) BasicNameValuePair(org.apache.http.message.BasicNameValuePair) ArrayList(java.util.ArrayList)

Aggregations

NameValuePair (org.apache.http.NameValuePair)713 BasicNameValuePair (org.apache.http.message.BasicNameValuePair)592 ArrayList (java.util.ArrayList)478 UrlEncodedFormEntity (org.apache.http.client.entity.UrlEncodedFormEntity)256 HttpPost (org.apache.http.client.methods.HttpPost)218 HttpResponse (org.apache.http.HttpResponse)150 IOException (java.io.IOException)125 HttpEntity (org.apache.http.HttpEntity)108 Test (org.junit.Test)85 URI (java.net.URI)79 Map (java.util.Map)72 HashMap (java.util.HashMap)68 HttpGet (org.apache.http.client.methods.HttpGet)66 CloseableHttpClient (org.apache.http.impl.client.CloseableHttpClient)59 UnsupportedEncodingException (java.io.UnsupportedEncodingException)58 CloseableHttpResponse (org.apache.http.client.methods.CloseableHttpResponse)55 URISyntaxException (java.net.URISyntaxException)52 Document (org.jsoup.nodes.Document)51 URIBuilder (org.apache.http.client.utils.URIBuilder)50 HttpClient (org.apache.http.client.HttpClient)46