List of usage examples for java.net HttpURLConnection getErrorStream
public InputStream getErrorStream()
From source file:AddressSvc.AddressSvc.java
public ValidateResult Validate(Address address) { //Create query/url String queryparams = address.toQuery(); String addrval = svcURL + "/1.0/address/validate?" + queryparams; URL url;//from ww w . j a va 2 s . c om HttpURLConnection conn; try { //Connect to specified URL with authorization header url = new URL(addrval); conn = (HttpURLConnection) url.openConnection(); String encoded = "Basic " + new String(Base64.encodeBase64((accountNum + ":" + license).getBytes())); //Create auth content conn.setRequestProperty("Authorization", encoded); //Add authorization header conn.disconnect(); ObjectMapper mapper = new ObjectMapper(); //Deserialization object if (conn.getResponseCode() != 200) //If we didn't get a success back, print out the error { ValidateResult vres = mapper.readValue(conn.getErrorStream(), ValidateResult.class); //Deserializes the response object return vres; } else //Otherwise, print out the validated address. { ValidateResult vres = mapper.readValue(conn.getInputStream(), ValidateResult.class); //Deserializes the response object return vres; } } catch (IOException e) { e.printStackTrace(); return null; } }
From source file:app.nichepro.fragmenttab.account.AbstractGetNameTask.java
/** * Contacts the user info server to get the profile of the user and extracts * the first name of the user from the profile. In order to authenticate * with the user info server the method first fetches an access token from * Google Play services.// w w w . j a v a 2 s . co m * * @throws IOException * if communication with user info server failed. * @throws JSONException * if the response from the server could not be parsed. */ private String fetchNameFromProfileServer() throws IOException, JSONException { String token = fetchToken(); String json = null; if (token == null) { // error has already been handled in fetchToken() return json; } URL url = new URL("https://www.googleapis.com/oauth2/v1/userinfo?access_token=" + token); HttpURLConnection con = (HttpURLConnection) url.openConnection(); int sc = con.getResponseCode(); if (sc == 200) { InputStream is = con.getInputStream(); // mActivity.googleLoginSuccess(readResponse(is)); json = readResponse(is); is.close(); return json; } else if (sc == 401) { GoogleAuthUtil.invalidateToken(mActivity, token); // onError("Server auth error, please try again.", null); error = "Server auth error, please try again."; Log.i(TAG, "Server auth error: " + readResponse(con.getErrorStream())); return json; } else { // onError("Server returned the following error code: " + sc, null); error = "Server auth error, please try again."; return json; } }
From source file:com.vizury.PushNotification.Engine.Sender.java
public MulticastResult sendMultiCastMessage(Message message, List<String> registrationIds, List<String> cookieList) throws IOException { logger.debug("Entering sendMessage"); if (nonNull(registrationIds).isEmpty()) { logger.error("SendMessage, registrationIds cannot be empty "); throw new IllegalArgumentException("registrationIds cannot be empty"); }/* w ww. j av a 2 s . co m*/ Map<Object, Object> jsonRequest = new HashMap<Object, Object>(); setJsonField(jsonRequest, PARAM_TIME_TO_LIVE, message.getTimeToLive()); setJsonField(jsonRequest, PARAM_COLLAPSE_KEY, message.getCollapseKey()); setJsonField(jsonRequest, PARAM_RESTRICTED_PACKAGE_NAME, message.getRestrictedPackageName()); setJsonField(jsonRequest, PARAM_DELAY_WHILE_IDLE, message.isDelayWhileIdle()); setJsonField(jsonRequest, PARAM_DRY_RUN, message.isDryRun()); setJsonField(jsonRequest, JSON_PAYLOAD, message.getPayloadData()); jsonRequest.put(JSON_REGISTRATION_IDS, registrationIds); String requestBody = JSONValue.toJSONString(jsonRequest); logger.debug("JSON request: " + requestBody); HttpURLConnection conn; int status; try { conn = post(GCM_SEND_ENDPOINT, "application/json", requestBody); status = conn.getResponseCode(); } catch (IOException e) { logger.debug("IOException posting to GCM" + e.getMessage()); return null; } String responseBody; if (status != 200) { try { responseBody = getAndClose(conn.getErrorStream()); logger.debug("JSON error response: " + responseBody); } catch (IOException e) { // ignore the exception since it will thrown an InvalidRequestException // anyways responseBody = "N/A"; logger.debug("Exception reading response: " + e.getMessage()); } throw new InvalidRequestException(status, responseBody); } try { responseBody = getAndClose(conn.getInputStream()); } catch (IOException e) { logger.error("IOException reading response, returning null result" + e.getMessage()); return null; } logger.debug("JSON response: " + responseBody); JSONParser parser = new JSONParser(); JSONObject jsonResponse; try { jsonResponse = (JSONObject) parser.parse(responseBody); int success = getNumber(jsonResponse, JSON_SUCCESS).intValue(); int failure = getNumber(jsonResponse, JSON_FAILURE).intValue(); int canonicalIds = getNumber(jsonResponse, JSON_CANONICAL_IDS).intValue(); long multicastId = getNumber(jsonResponse, JSON_MULTICAST_ID).longValue(); MulticastResult.Builder builder = new MulticastResult.Builder(success, failure, canonicalIds, multicastId); @SuppressWarnings("unchecked") List<Map<String, Object>> results = (List<Map<String, Object>>) jsonResponse.get(JSON_RESULTS); int count = 0; if (results != null) { for (Map<String, Object> jsonResult : results) { String messageId = (String) jsonResult.get(JSON_MESSAGE_ID); String canonicalRegId = (String) jsonResult.get(TOKEN_CANONICAL_REG_ID); String error = (String) jsonResult.get(JSON_ERROR); String cookie = cookieList.get(count); count++; Result result = new Result.Builder().messageId(messageId) .canonicalRegistrationId(canonicalRegId).errorCode(error).cookieValue(cookie).build(); builder.addResult(result); } } logger.debug("Finished sendMessage"); return builder.build(); } catch (ParseException e) { throw newIoException(responseBody, e); } catch (CustomParserException e) { throw newIoException(responseBody, e); } }
From source file:eu.codeplumbers.cosi.api.tasks.GetPlacesTask.java
@Override protected List<Place> doInBackground(Void... voids) { URL urlO = null;/*www . ja va2 s . c o m*/ try { urlO = new URL(url); HttpURLConnection conn = (HttpURLConnection) urlO.openConnection(); conn.setConnectTimeout(5000); conn.setRequestProperty("Content-Type", "application/json; charset=UTF-8"); conn.setRequestProperty("Authorization", authHeader); conn.setDoInput(true); conn.setRequestMethod("POST"); // read the response int status = conn.getResponseCode(); InputStream in = null; if (status >= HttpURLConnection.HTTP_BAD_REQUEST) { in = conn.getErrorStream(); } else { in = conn.getInputStream(); } StringWriter writer = new StringWriter(); IOUtils.copy(in, writer, "UTF-8"); String result = writer.toString(); JSONArray jsonArray = new JSONArray(result); if (jsonArray != null) { if (jsonArray.length() > 0) { for (int i = 0; i < jsonArray.length(); i++) { String version = "0"; if (jsonArray.getJSONObject(i).has("version")) { version = jsonArray.getJSONObject(i).getString("version"); } JSONObject placeJson = jsonArray.getJSONObject(i).getJSONObject("value"); Place place = Place.getByLocation(placeJson.get("description").toString(), placeJson.get("latitude").toString(), placeJson.get("longitude").toString()); if (place == null) { place = new Place(placeJson); } else { place.setDeviceId(placeJson.getString("deviceId")); place.setAddress(placeJson.getString("address")); place.setDateAndTime(placeJson.getString("dateAndTime")); place.setLongitude(placeJson.getDouble("longitude")); place.setLatitude(placeJson.getDouble("latitude")); place.setRemoteId(placeJson.getString("_id")); } publishProgress("Saving place : " + place.getAddress()); place.save(); allPlaces.add(place); } } else { publishProgress("Your Cozy has no places stored."); return allPlaces; } } else { errorMessage = "Failed to parse API response"; } in.close(); conn.disconnect(); } catch (MalformedURLException e) { e.printStackTrace(); errorMessage = e.getLocalizedMessage(); } catch (ProtocolException e) { errorMessage = e.getLocalizedMessage(); e.printStackTrace(); } catch (IOException e) { errorMessage = e.getLocalizedMessage(); e.printStackTrace(); } catch (JSONException e) { errorMessage = e.getLocalizedMessage(); e.printStackTrace(); } return allPlaces; }
From source file:com.richmond.riddler.AbstractGetNameTask.java
/** * Contacts the user info server to get the profile of the user and extracts the first name * of the user from the profile. In order to authenticate with the user info server the method * first fetches an access token from Google Play services. * @throws IOException if communication with user info server failed. * @throws JSONException if the response from the server could not be parsed. *///w ww. ja v a 2s.c om private void fetchNameFromProfileServer() throws IOException, JSONException { String token = fetchToken(); if (token == null) { // error has already been handled in fetchToken() return; } URL url = new URL("https://www.googleapis.com/oauth2/v1/userinfo?access_token=" + token); HttpURLConnection con = (HttpURLConnection) url.openConnection(); int sc = con.getResponseCode(); if (sc == 200) { InputStream is = con.getInputStream(); mName = getFirstName(readResponse(is)); //mActivity.setName(name); mActivity.show("Hello " + mName + "!"); setAuth(true); is.close(); return; } else if (sc == 401) { GoogleAuthUtil.invalidateToken(mActivity, token); onError("Server auth error, please try again.", null); Log.i(TAG, "Server auth error: " + readResponse(con.getErrorStream())); return; } else { onError("Server returned the following error code: " + sc, null); return; } }
From source file:com.gmobi.poponews.util.HttpHelper.java
private static Response doRequest(String url, Object raw, int method) { disableSslCheck();/*from w w w . ja v a 2 s.c om*/ boolean isJson = raw instanceof JSONObject; String body = raw == null ? null : raw.toString(); Response response = new Response(); HttpURLConnection connection = null; try { URL httpURL = new URL(url); connection = (HttpURLConnection) httpURL.openConnection(); connection.setConnectTimeout(15000); connection.setReadTimeout(30000); connection.setUseCaches(false); if (method == HTTP_POST) connection.setRequestMethod("POST"); if (body != null) { if (isJson) { connection.setRequestProperty("Accept", "application/json"); connection.setRequestProperty("Content-Type", "application/json"); } OutputStream os = connection.getOutputStream(); OutputStreamWriter osw = new OutputStreamWriter(os); osw.write(body); osw.flush(); osw.close(); } InputStream in = connection.getInputStream(); response.setBody(FileHelper.readText(in, "UTF-8")); response.setStatusCode(connection.getResponseCode()); in.close(); connection.disconnect(); connection = null; } catch (Exception e) { Logger.error(e); try { if ((connection != null) && (response.getBody() == null) && (connection.getErrorStream() != null)) { response.setBody(FileHelper.readText(connection.getErrorStream(), "UTF-8")); } } catch (Exception ex) { Logger.error(ex); } } return response; }
From source file:com.pubkit.platform.notification.gcm.GcmConnection.java
/** * Sends a message without retrying in case of service unavailability. See * {@link #send(Message, List, int)} for more info. * * @return {@literal true} if the message was sent successfully, * {@literal false} if it failed but could be retried. * @throws IllegalArgumentException/* w w w . j a v a 2s. co m*/ * if registrationIds is {@literal null} or empty. * @throws InvalidRequestException * if GCM didn't returned a 200 status. * @throws IOException * if message could not be sent or received. */ public MulticastResult sendNoRetry(Message message, List<String> registrationIds) throws IOException { if (nonNull(registrationIds).isEmpty()) { throw new IllegalArgumentException("registrationIds cannot be empty"); } Map<Object, Object> jsonRequest = new HashMap<Object, Object>(); setJsonField(jsonRequest, Constants.PARAM_TIME_TO_LIVE, message.getTimeToLive()); setJsonField(jsonRequest, Constants.PARAM_COLLAPSE_KEY, message.getCollapseKey()); setJsonField(jsonRequest, Constants.PARAM_DELAY_WHILE_IDLE, message.isDelayWhileIdle()); jsonRequest.put(Constants.JSON_REGISTRATION_IDS, registrationIds); Map<String, String> payload = message.getData(); if (!payload.isEmpty()) { jsonRequest.put(Constants.JSON_PAYLOAD, payload); } String requestBody = JSONValue.toJSONString(jsonRequest); logger.finest("JSON request: " + requestBody); HttpURLConnection conn = post(Constants.GCM_SEND_ENDPOINT, "application/json", requestBody); int status = conn.getResponseCode(); String responseBody; if (status != 200) { responseBody = getString(conn.getErrorStream()); logger.finest("JSON error response: " + responseBody); throw new InvalidRequestException(status, responseBody); } responseBody = getString(conn.getInputStream()); logger.finest("JSON response: " + responseBody); JSONParser parser = new JSONParser(); JSONObject jsonResponse; try { jsonResponse = (JSONObject) parser.parse(responseBody); int success = getNumber(jsonResponse, Constants.JSON_SUCCESS).intValue(); int failure = getNumber(jsonResponse, Constants.JSON_FAILURE).intValue(); int canonicalIds = getNumber(jsonResponse, Constants.JSON_CANONICAL_IDS).intValue(); long multicastId = getNumber(jsonResponse, Constants.JSON_MULTICAST_ID).longValue(); MulticastResult.Builder builder = new MulticastResult.Builder(success, failure, canonicalIds, multicastId); @SuppressWarnings("unchecked") List<Map<String, Object>> results = (List<Map<String, Object>>) jsonResponse .get(Constants.JSON_RESULTS); if (results != null) { for (Map<String, Object> jsonResult : results) { String messageId = (String) jsonResult.get(Constants.JSON_MESSAGE_ID); String canonicalRegId = (String) jsonResult.get(Constants.TOKEN_CANONICAL_REG_ID); String error = (String) jsonResult.get(Constants.JSON_ERROR); Result result = new Result.Builder().messageId(messageId) .canonicalRegistrationId(canonicalRegId).errorCode(error).build(); builder.addResult(result); } } MulticastResult multicastResult = builder.build(); return multicastResult; } catch (ParseException e) { throw newIoException(responseBody, e); } catch (CustomParserException e) { throw newIoException(responseBody, e); } }
From source file:org.sufficientlysecure.keychain.keyimport.HkpKeyServer.java
private String query(String request) throws QueryException, HttpError { InetAddress ips[];/*ww w. ja v a 2 s .c o m*/ try { ips = InetAddress.getAllByName(mHost); } catch (UnknownHostException e) { throw new QueryException(e.toString()); } for (int i = 0; i < ips.length; ++i) { try { String url = "http://" + ips[i].getHostAddress() + ":" + mPort + request; Log.d(Constants.TAG, "hkp keyserver query: " + url); URL realUrl = new URL(url); HttpURLConnection conn = (HttpURLConnection) realUrl.openConnection(); conn.setConnectTimeout(5000); conn.setReadTimeout(25000); conn.connect(); int response = conn.getResponseCode(); if (response >= 200 && response < 300) { return readAll(conn.getInputStream(), conn.getContentEncoding()); } else { String data = readAll(conn.getErrorStream(), conn.getContentEncoding()); throw new HttpError(response, data); } } catch (MalformedURLException e) { // nothing to do, try next IP } catch (IOException e) { // nothing to do, try next IP } } throw new QueryException("querying server(s) for '" + mHost + "' failed"); }
From source file:org.thialfihar.android.apg.keyimport.HkpKeyserver.java
private String query(String request) throws QueryFailedException, HttpError { InetAddress ips[];//from w w w . j a v a 2s . c o m try { ips = InetAddress.getAllByName(mHost); } catch (UnknownHostException e) { throw new QueryFailedException(e.toString()); } for (int i = 0; i < ips.length; ++i) { try { String url = "http://" + ips[i].getHostAddress() + ":" + mPort + request; Log.d(Constants.TAG, "hkp keyserver query: " + url); URL realUrl = new URL(url); HttpURLConnection conn = (HttpURLConnection) realUrl.openConnection(); conn.setConnectTimeout(5000); conn.setReadTimeout(25000); conn.connect(); int response = conn.getResponseCode(); if (response >= 200 && response < 300) { return readAll(conn.getInputStream(), conn.getContentEncoding()); } else { String data = readAll(conn.getErrorStream(), conn.getContentEncoding()); throw new HttpError(response, data); } } catch (MalformedURLException e) { // nothing to do, try next IP } catch (IOException e) { // nothing to do, try next IP } } throw new QueryFailedException("querying server(s) for '" + mHost + "' failed"); }
From source file:com.mnxfst.stream.listener.webtrends.WebtrendsTokenRequest.java
private String httpPost(Map<String, String> requestParams) throws Exception { final URL url = new URL(authUrl); final StringBuilder data = new StringBuilder(); for (String key : requestParams.keySet()) data.append(String.format("%s=%s&", key, requestParams.get(key))); final String dataString = data.toString(); final String formData = dataString.substring(0, dataString.length() - 1); final HttpURLConnection connection = (HttpURLConnection) url.openConnection(); connection.setRequestMethod("POST"); connection.setRequestProperty("Content-type", "application/x-www-form-urlencoded"); connection.setDoOutput(true);/*www. j a v a 2 s .co m*/ final OutputStream outputStream = connection.getOutputStream(); final OutputStreamWriter outputStreamWriter = new OutputStreamWriter(outputStream); outputStreamWriter.write(formData); outputStreamWriter.flush(); InputStream is = connection.getResponseCode() != 400 ? connection.getInputStream() : connection.getErrorStream(); final BufferedReader rd = new BufferedReader(new InputStreamReader(is)); final StringBuffer stringBuffer = new StringBuffer(); String line; while ((line = rd.readLine()) != null) stringBuffer.append(line); outputStreamWriter.close(); rd.close(); if (connection.getResponseCode() == 400) throw new Exception("error: " + stringBuffer.toString()); return stringBuffer.toString(); }