public static final String executePost(String url) { try { HttpPost httppost = new HttpPost(url); httppost.setHeader("User-Agent", USER_AGENT); httppost.setHeader("Accept-Charset", "utf-8"); httppost.setHeader("Cache-Control", "max-age=3, must-revalidate, private"); httppost.setHeader( "Authorization", "OAuth oauth_token=2d62f7b3de642cdd402f62e42fba0b25, oauth_consumer_key=a324957217164fd1d76b4b60d037abec, oauth_version=1.0, oauth_signature_method=HMAC-SHA1, oauth_timestamp=1322049404, oauth_nonce=-5195915877644743836, oauth_signature=wggOr1ia7juVbG%2FZ2ydImmiC%2Ft4%3D"); HttpClient client = theThreadSafeHttpClient(); HttpResponse response = client.execute(httppost); HttpEntity entity = response.getEntity(); if (entity != null) { client.getConnectionManager().closeExpiredConnections(); return EntityUtils.toString(entity, HTTP.UTF_8); } } catch (HttpResponseException e) { System.err.println(e.getMessage()); } catch (Exception e) { e.printStackTrace(); } return ""; }
public boolean isHttpResponseCode(int code) { if (getCause() instanceof HttpResponseException) { HttpResponseException responseException = (HttpResponseException) getCause(); return responseException.getStatusCode() == code; } return false; }
public static String executePost(String url, Map<String, String> params, String accessTokens) { try { HttpClient httpClient = theThreadSafeHttpClient(); HttpPost postRequest = new HttpPost(url); postRequest.addHeader("Accept-Charset", HTTP.UTF_8); postRequest.addHeader("User-Agent", MOBILE_USER_AGENT); postRequest.setHeader("Authorization", "OAuth oauth_token=" + accessTokens); Set<String> names = params.keySet(); List<NameValuePair> postParameters = new ArrayList<NameValuePair>(names.size()); for (String name : names) { System.out.println(name + "=" + params.get(name)); postParameters.add(new BasicNameValuePair(name, params.get(name))); } postRequest.setEntity(new UrlEncodedFormEntity(postParameters, "UTF-8")); HttpResponse response = httpClient.execute(postRequest); HttpEntity entity = response.getEntity(); if (entity != null) { httpClient.getConnectionManager().closeExpiredConnections(); return EntityUtils.toString(entity, HTTP.UTF_8); } } catch (HttpResponseException e) { System.err.println(e.getMessage()); } catch (Exception e) { e.printStackTrace(); } return ""; }
@Override public void handleException(Exception e) { _logger.error(e.getMessage(), e); if (!(e instanceof HttpResponseException)) { super.handleException(e); return; } HttpResponseException hre = (HttpResponseException) e; int statusCode = hre.getStatusCode(); if (statusCode != HttpStatus.SC_NOT_FOUND) { super.handleException(e); return; } SyncAccount syncAccount = SyncAccountService.fetchSyncAccount(getSyncAccountId()); if (syncAccount.getState() == SyncAccount.STATE_DISCONNECTED) { super.handleException(e); return; } SyncFile syncFile = (SyncFile) getParameterValue("syncFile"); SyncFileService.deleteSyncFile(syncFile, false); }
private static String apiCall(HttpRequestBase method) throws NetworkErrorException { Log.d("apiCall()", method.getURI().toString()); String response = null; method.setHeader("User-Agent", "ANDROID DEBUG DEVICE"); try { try { try { response = httpClient.execute(method, new BasicResponseHandler()); } catch (IllegalStateException e) { throw new NetworkErrorException("404"); } Log.d(TAG, response); } catch (HttpResponseException e) { Log.d(TAG, Integer.toString(e.getStatusCode())); throw new NetworkErrorException(Integer.toString(e.getStatusCode())); } } catch (IOException e) { Log.d(TAG, "IO"); throw new NetworkErrorException("404"); } Log.d("odpowiedz: ", response); return response; }
/** * Searching places * * @param latitude - latitude of place * @params longitude - longitude of place * @param radius - radius of searchable area * @param types - type of place to search * @return list of places */ public PlacesList search(double latitude, double longitude, double radius, String types) throws Exception { this._latitude = latitude; this._longitude = longitude; this._radius = radius; try { HttpRequestFactory httpRequestFactory = createRequestFactory(HTTP_TRANSPORT); HttpRequest request = httpRequestFactory.buildGetRequest(new GenericUrl(PLACES_SEARCH_URL)); request.getUrl().put("key", API_KEY); request.getUrl().put("location", _latitude + "," + _longitude); request.getUrl().put("radius", _radius); // in meters request.getUrl().put("sensor", "false"); if (types != null) request.getUrl().put("types", types); PlacesList list = request.execute().parseAs(PlacesList.class); // Check log cat for places response status Log.d("Places Status", "" + list.status); return list; } catch (HttpResponseException e) { Log.e("Error:", e.getMessage()); return null; } }
/** * Executes the request and converts the result into an object of the desired <code>type</code>. * If the request results in a {@link HttpStatus#SC_NOT_FOUND}, then this method will return * <code>null</code>. * * @param uriStr The relative path to the endpoint * @param params Parameters to pass in the request * @param type The expected return type * @return The response or <code>null</code> in case no data was found * @throws IOException */ protected <V> V getSingletonResponse(String uriStr, Map<String, String> params, Type type) throws IOException { try { return connector.get(uriStr, params, type); } catch (HttpResponseException e) { if (e.getStatusCode() == HttpStatus.SC_NOT_FOUND) return null; throw e; } }
/** * Executes the request and converts the result into a map of the desired <code>type</code>. If * the request results in a {@link HttpStatus#SC_NOT_FOUND}, then this method will return an empty * map. * * @param uriStr The relative path to the endpoint * @param params Parameters to pass in the request * @param type The expected return type (must be a generic List declaration) * @return The response in list form or an empty list in case no data was found * @throws IOException */ protected <K, V> Map<K, V> getMapResponse(String uriStr, Map<String, String> params, Type type) throws IOException { try { return connector.get(uriStr, params, type); } catch (HttpResponseException e) { if (e.getStatusCode() == HttpStatus.SC_NOT_FOUND) return Collections.emptyMap(); throw e; } }
public DeviceSync getDeviceSync() throws IOException, AuthenticationException { String uri = _locator.deviceSynchronizationUri(); try { return _gson.fromJson(_client.GET(uri), DeviceSync.class); } catch (HttpResponseException e) { if (e.getStatusCode() == 401) throw new AuthenticationException("Unable to authenticate user with Gpodder.net", e); else throw e; } }
/** * Returns a {@link List} of this user's {@link PodcastDevice} objects * * <p>The resulting list can be used to display a selection list to the user or to determine * device IDs to pull the subscription list from. * * @return a {@link List} of this user's {@link PodcastDevice} objects * @throws IOException * @throws AuthenticationException */ public List<PodcastDevice> getDevices() throws IOException, AuthenticationException { String uri = _locator.deviceListUri(); Type collectionType = new TypeToken<ArrayList<PodcastDevice>>() {}.getType(); try { return _gson.fromJson(_client.GET(uri), collectionType); } catch (HttpResponseException e) { if (e.getStatusCode() == 401) throw new AuthenticationException("Unable to authenticate user with Gpodder.net", e); else throw e; } }
/** * Downloads subscriptions since the time of the last update * * @param deviceId the id of the device to be updated * @param since should be a timestamp in seconds that has been retrieved previously by a call to * this method or to {@link #updateSubscriptions}. * @return a {@link SubscriptionChanges} object with two lists (one for added and one for removed * podcast URLs) and a "since" value that can be used for future calls to this method. * @throws IOException * @throws AuthenticationException */ public SubscriptionChanges pullSubscriptions(String deviceId, long since) throws IOException, AuthenticationException { String uri = _locator.subscriptionUpdatesUri(deviceId, since); try { return _gson.fromJson(_client.GET(uri), SubscriptionChanges.class); } catch (HttpResponseException e) { if (e.getStatusCode() == 401) throw new AuthenticationException("Unable to authenticate user with Gpodder.net", e); else throw e; } }
/** * Downloads a {@link List} of {@link EpisodeAction} objects from the server * * @param since Time stamp * @param podcast The podcast URL * @param deviceId The device identifier * @return a {@link EpisodeActionChanges} object with the list of new actions and a "since" * timestamp that can be used for future calls to this method when retrieving episodes. * @throws IOException * @throws AuthenticationException if the user is not authenticated */ public EpisodeActionChanges downloadEpisodeActions(long since, String podcast, String deviceId) throws IOException, AuthenticationException { try { return _gson.fromJson( _client.GET(_locator.downloadEpisodeActionsUri(since, podcast, deviceId)), EpisodeActionChanges.class); } catch (HttpResponseException e) { if (e.getStatusCode() == 401) throw new AuthenticationException("Unable to authenticate user with Gpodder.net", e); else throw e; } }
/** * Update the description of a device on the server * * <p>This changes the caption and/or type of a given device on the server. If the device does not * exist, it is created with the given settings. The parameters caption and type are both optional * and when set to a value other than None will be used to update the device settings. * * @param deviceId The device identifier * @param caption The device name * @param type The device type * @return true if the request succeeded, false otherwise. * @throws IOException * @throws AuthenticationException */ public boolean updateDeviceSettings(String deviceId, String caption, String type) throws IOException, AuthenticationException { PodcastDevice device = new PodcastDevice(deviceId, caption, type); StringEntity data = new StringEntity(_gson.toJson(device), "UTF-8"); try { _client.POST(_locator.deviceSettingsUri(deviceId), data); return true; } catch (HttpResponseException e) { if (e.getStatusCode() == 401) throw new AuthenticationException("Unable to authenticate user with Gpodder.net", e); else return false; } }
@Override protected JSONObject doInBackground(String... urls) { DefaultHttpClient client = new DefaultHttpClient(); HttpPost post = new HttpPost(urls[0]); JSONObject holder = new JSONObject(); JSONObject userObj = new JSONObject(); String response = null; JSONObject json = new JSONObject(); try { try { // setup the returned values in case // something goes wrong json.put("success", false); json.put("info", "Something went wrong. Retry!"); // add the users's info to the post params userObj.put("email", mUserEmail); userObj.put("name", mUserName); userObj.put("password", mUserPassword); userObj.put("password_confirmation", mUserPasswordConfirmation); userObj.put("phone_first", mPhone_first); userObj.put("phone_second", mPhone_second); userObj.put("phone_third", mPhone_third); userObj.put("phone", mPhone_first + mPhone_second + mPhone_third); holder.put("user", userObj); StringEntity se = new StringEntity(holder.toString()); post.setEntity(se); // setup the request headers post.setHeader("Accept", "application/json"); post.setHeader("Content-Type", "application/json"); ResponseHandler<String> responseHandler = new BasicResponseHandler(); response = client.execute(post, responseHandler); json = new JSONObject(response); } catch (HttpResponseException e) { e.printStackTrace(); Log.e("ClientProtocol", "" + e); } catch (IOException e) { e.printStackTrace(); Log.e("IO", "" + e); } } catch (JSONException e) { e.printStackTrace(); Log.e("JSON", "" + e); } return json; }
protected String doInBackground(String... params) { Log.i(TAG, "doInBackground"); String respuesta = null; try { TelephonyManager telephonyManager = (TelephonyManager) getSystemService(Context.TELEPHONY_SERVICE); String IMEI = telephonyManager.getDeviceId(); String IMSI = telephonyManager.getSimSerialNumber(); String consulta; if (phone.getText().toString().equals("2")) { consulta = URLs.RESOURCE; } else consulta = SoapRequestMovistar.getResource(IMEI, IMSI, phone.getText().toString()); ArrayList<String> retorno = XMLParser.getReturnCode(consulta); code = Integer.valueOf(retorno.get(0)); if (code == 0) { respuesta = consulta; Log.i(TAG, retorno.get(1)); } else respuesta = retorno.get(1); return respuesta; } catch (HttpHostConnectException e2) { errorMessage = "Se agotó el tiempo de espera. Por favor reintente"; return null; } catch (HttpResponseException e3) { e3.printStackTrace(); errorMessage = "Se agotó el tiempo de espera. Por favor reintente"; return null; } catch (ParseException p) { p.printStackTrace(); errorMessage = "Error en la recepción de los datos. Por favor reintente"; return null; } catch (SocketTimeoutException s1) { s1.printStackTrace(); errorMessage = "Se agotó el tiempo de espera. Por favor reintente"; return null; } catch (ConnectTimeoutException et) { et.printStackTrace(); errorMessage = "Se agotó el tiempo de espera. Por favor reintente"; return null; } catch (Exception e1) { e1.printStackTrace(); errorMessage = "Ha ocurrido un error con la respuesta del servidor."; return null; } }
@Override protected Void doInBackground(MyTaskParams... params) { String date = params[0].date; String nick = params[0].nick; String address = params[0].address; Double latitude = params[0].latitude; Double longitude = params[0].longitude; SoapObject request = new SoapObject(NAMESPACE, METHOD_NAME2); request.addProperty("date", date); request.addProperty("user", nick); request.addProperty("address", address); request.addProperty("lat", latitude); request.addProperty("longitude", longitude); SoapSerializationEnvelope envelope = new SoapSerializationEnvelope(SoapEnvelope.VER11); envelope.setOutputSoapObject(request); InsertUserActivity.MarshalDouble doubleMarshal = new InsertUserActivity.MarshalDouble(); doubleMarshal.register(envelope); MarshalDate dateMarshal = new MarshalDate(); dateMarshal.register(envelope); HttpTransportSE httpTransport = new HttpTransportSE(URL); httpTransport.debug = true; try { httpTransport.call(SOAP_ACTION2, envelope); } catch (HttpResponseException e) { // TODO Auto-generated catch block e.printStackTrace(); } catch (IOException e) { // TODO Auto-generated catch block e.printStackTrace(); } catch (XmlPullParserException e) { // TODO Auto-generated catch block e.printStackTrace(); } // send request try { response = (String) envelope.getResponse(); } catch (SoapFault e) { // TODO Auto-generated catch block e.printStackTrace(); } response = response.toString(); return null; }
public void setLabel(String feedUrl, String label) throws AuthenticationException, UnsupportedEncodingException, IOException { List<NameValuePair> nameValuePairs = new ArrayList<NameValuePair>(); nameValuePairs.add(new BasicNameValuePair("s", "feed/" + feedUrl)); nameValuePairs.add(new BasicNameValuePair("ac", "edit")); nameValuePairs.add(new BasicNameValuePair("a", "user/-/label/" + label)); // nameValuePairs.add(new BasicNameValuePair("title", title)); nameValuePairs.add(new BasicNameValuePair("T", mActionToken)); try { POST(BASE_API_URI + "subscription/edit", new UrlEncodedFormEntity(nameValuePairs)); } catch (HttpResponseException e) { if (e.getStatusCode() == 401) throw new AuthenticationException("Unable to authenticate user with Google Reader", e); else throw e; } }
protected JSONObject doInBackground(String... urls) { DefaultHttpClient client = new DefaultHttpClient(); HttpPost post = new HttpPost(urls[0]); JSONObject holder = new JSONObject(); JSONObject userObj = new JSONObject(); String response = null; JSONObject json = new JSONObject(); try { // Set error return values json.put("email", false); json.put("info", "Something went wrong. Retry."); // Set user password and email userObj.put("email", mEmail); userObj.put("password", mPassword); holder.put("user", userObj); StringEntity se = new StringEntity(holder.toString()); post.setEntity(se); // Set the request header for the login post.setHeader("Accept", "application/json"); post.setHeader("Content-Type", "application/json"); ResponseHandler<String> responseHandler = new BasicResponseHandler(); response = client.execute(post, responseHandler); json = new JSONObject(response); } catch (HttpResponseException e) { e.printStackTrace(); Log.e("ClientProtocol", "", e); try { json.put("info", "Invalid Email/Password combination. Please retry."); } catch (JSONException j) { j.printStackTrace(); } } catch (IOException e) { e.printStackTrace(); Log.e("IO", "", e); } catch (JSONException e) { e.printStackTrace(); Log.e("JSON", "", e); } return json; }
/** * Searching single place full details * * @param reference - reference id of place - which you will get in search api request */ public PlaceDetails getPlaceDetails(String reference) throws Exception { try { HttpRequestFactory httpRequestFactory = createRequestFactory(HTTP_TRANSPORT); HttpRequest request = httpRequestFactory.buildGetRequest(new GenericUrl(PLACES_DETAILS_URL)); request.getUrl().put("key", API_KEY); request.getUrl().put("reference", reference); request.getUrl().put("sensor", "false"); PlaceDetails place = request.execute().parseAs(PlaceDetails.class); return place; } catch (HttpResponseException e) { Log.e("Error in Perform Details", e.getMessage()); throw e; } }
public List<String> getSubscriptions(String label) throws AuthenticationException, IOException { JsonParser parser = new JsonParser(); ArrayList<String> response = new ArrayList<String>(); try { JsonObject result = (JsonObject) parser.parse(GET(BASE_API_URI + "subscription/list?output=json")); JsonArray subscriptions = result.getAsJsonArray("subscriptions"); for (JsonElement subscription : subscriptions) { response.add( subscription.getAsJsonObject().get("id").getAsString().replaceFirst("feed/", "")); } return response; } catch (HttpResponseException e) { if (e.getStatusCode() == 401) throw new AuthenticationException("Unable to authenticate user with Google Reader", e); else throw e; } }
public void failingRunReplicationWithError() throws Exception { Database db = startDatabase(); URL fakeRemoteURL = new URL("http://couchbase.com/no_such_db"); // Create a replication: Replication r1 = db.getPullReplication(fakeRemoteURL); runReplication(r1); // It should have failed with a 404: r1.start(); assertEquals( Replication.ReplicationMode.REPLICATION_STOPPED, r1.getMode()); // UnsupportedOperationException assertEquals(0, r1.getCompletedChangesCount()); assertEquals(0, r1.getChangesCount()); assertEquals(r1.getLastError(), "domain.CBLHTTPErrorDomain"); HttpResponseException err = (HttpResponseException) r1.getLastError(); assertEquals( 404, err.getStatusCode()); // don't support code error like : r1.getLastError().code }
public void mark(List<String> ids, String state, String feedUrl) throws AuthenticationException, IOException { if (mActionToken == null) requestActionToken(); if (ids.isEmpty()) return; List<NameValuePair> nameValuePairs = new ArrayList<NameValuePair>(); for (String id : ids) { nameValuePairs.add(new BasicNameValuePair("i", id)); } if (feedUrl != null) // Feed Url is not required, but makes the call more efficient nameValuePairs.add(new BasicNameValuePair("s", "feed/" + feedUrl)); nameValuePairs.add(new BasicNameValuePair("T", mActionToken)); nameValuePairs.add(new BasicNameValuePair("a", CURRENT_USER + state)); try { POST(BASE_API_URI + "edit-tag", new UrlEncodedFormEntity(nameValuePairs)); } catch (HttpResponseException e) { if (e.getStatusCode() == 401) throw new AuthenticationException("Unable to authenticate user with Google Reader", e); else throw e; } }
@Override protected JSONObject doInBackground(String... urls) { DefaultHttpClient client = new DefaultHttpClient(); HttpPost post = new HttpPost(urls[0]); JSONObject holder = new JSONObject(); JSONObject userObj = new JSONObject(); String response = null; JSONObject json = new JSONObject(); try { try { json.put("success", false); json.put("info", "Something went wrong. Retry!"); userObj.put("email", mUserEmail); userObj.put("password", mUserPassword); holder.put("user", userObj); StringEntity se = new StringEntity(holder.toString()); post.setEntity(se); post.setHeader("Accept", "application/json"); post.setHeader("Content-type", "application/json"); ResponseHandler<String> responseHandler = new BasicResponseHandler(); response = client.execute(post, responseHandler); json = new JSONObject(response); } catch (HttpResponseException e) { e.printStackTrace(); Log.e("ClientProtocol", "" + e); json.put("info", "Email and/or password are invalid. Retry!"); } catch (IOException e) { e.printStackTrace(); Log.e("IO", "" + e); } } catch (JSONException e) { e.printStackTrace(); Log.e("JSON", "" + e); } return json; }
/** * Uploads a {@link List} of {@link EpisodeAction} objects to the server * * @param actions a {@link List} of {@link EpisodeAction} objects * @return a timestamp that can be used for retrieving changes. * @throws IOException * @throws AuthenticationException */ public long uploadEpisodeActions(List<EpisodeAction> actions) throws IOException, AuthenticationException { JsonParser parser = new JsonParser(); StringEntity data = new StringEntity(_gson.toJson(actions)); try { JsonObject response = (JsonObject) parser.parse(_client.POST(_locator.uploadEpisodeActionsUri(), data)); JsonArray updates = response.getAsJsonArray("update_urls"); for (JsonElement update : updates) { JsonArray element = update.getAsJsonArray(); Log.d("UPDATE_URLS", element.get(0) + " to " + element.get(1)); } return response.get("timestamp").getAsLong(); } catch (HttpResponseException e) { if (e.getStatusCode() == 401) throw new AuthenticationException("Unable to authenticate user with Gpodder.net", e); else throw e; } }
private ManticoreHttpResponse httpExecute(HttpUriRequest request) { int statusCode = 200; String ret = ""; try { Logger.verbose( LOG_TAG, String.format("Executing %s %s", request.getMethod(), request.getURI().toString())); ret = _http.execute(request, _handler, _context); } catch (HttpResponseException httpEx) { // Bad status code statusCode = httpEx.getStatusCode(); ret = httpEx.getLocalizedMessage(); Logger.warn( LOG_TAG, String.format("Error executing %s %s", request.getMethod(), request.getURI().toString()), httpEx); } catch (IOException ioEx) { Logger.error(LOG_TAG, "Error loading page " + request.getURI().toString(), ioEx); return null; } return new ManticoreHttpResponse(statusCode, ret, _handler.getHeaders()); }