List of usage examples for java.net HttpURLConnection getErrorStream
public InputStream getErrorStream()
From source file:com.portfolio.data.attachment.FileServlet.java
void RetrieveAnswer(HttpURLConnection connection, HttpServletResponse response, String referer) throws MalformedURLException, IOException { /// Receive answer InputStream in;/*w w w .j a v a 2 s . c om*/ try { in = connection.getInputStream(); } catch (Exception e) { System.out.println(e.toString()); in = connection.getErrorStream(); } InitAnswer(connection, response, referer); /// Write back data DataInputStream stream = new DataInputStream(in); byte[] buffer = new byte[1024]; int size; ServletOutputStream out = null; try { out = response.getOutputStream(); while ((size = stream.read(buffer, 0, buffer.length)) != -1) out.write(buffer, 0, size); } catch (Exception e) { System.out.println(e.toString()); System.out.println("Writing messed up!"); } finally { in.close(); out.flush(); // close() should flush already, but Tomcat 5.5 doesn't out.close(); } }
From source file:net.technicpack.minecraftcore.mojang.auth.AuthenticationService.java
private String postJson(String url, String data) throws IOException { byte[] rawData = data.getBytes("UTF-8"); HttpURLConnection connection = (HttpURLConnection) new URL(url).openConnection(); connection.setUseCaches(false);/*w ww . j a v a 2 s. c o m*/ connection.setDoOutput(true); connection.setDoInput(true); connection.setConnectTimeout(15000); connection.setReadTimeout(15000); connection.setRequestMethod("POST"); connection.setRequestProperty("Content-Type", "application/json; charset=utf-8"); connection.setRequestProperty("Content-Length", rawData.length + ""); connection.setRequestProperty("Content-Language", "en-US"); DataOutputStream writer = new DataOutputStream(connection.getOutputStream()); writer.write(rawData); writer.flush(); writer.close(); InputStream stream = null; String returnable = null; try { stream = connection.getInputStream(); returnable = IOUtils.toString(stream, Charsets.UTF_8); } catch (IOException e) { stream = connection.getErrorStream(); if (stream == null) { throw e; } } finally { try { if (stream != null) stream.close(); } catch (IOException e) { } } return returnable; }
From source file:com.github.gorbin.asne.instagram.InstagramSocialNetwork.java
private String checkInputStream(HttpURLConnection connection) { String errorType = null, code = null, errorMessage = null; InputStream inputStream = connection.getErrorStream(); String response = streamToString(inputStream); try {/*from w w w. ja v a 2 s .c o m*/ JSONObject jsonObject = (JSONObject) new JSONTokener(response).nextValue(); JSONObject jsonResponse = jsonObject.getJSONObject("meta"); if (jsonResponse.has("error_type")) { errorType = jsonResponse.getString("error_type"); } if (jsonResponse.has("code")) { code = jsonResponse.getString("code"); } if (jsonResponse.has("error_message")) { errorMessage = jsonResponse.getString("error_message"); } return "ERROR TYPE: " + errorType + " ERROR CODE: " + code + " ERROR MESSAGE: " + errorMessage; } catch (JSONException e) { return e.getMessage(); } }
From source file:com.example.socketmobile.android.warrantychecker.network.WarrantyCheck.java
private Object fetchWarranty(String id, String authString, String query) throws IOException { InputStream is = null;/*from w w w.j a va2 s .com*/ RegistrationApiResponse result = null; RegistrationApiErrorResponse errorResult = null; String authHeader = "Basic " + Base64.encodeToString(authString.getBytes(), Base64.NO_WRAP); try { URL url = new URL(baseUrl + id + "?" + query); HttpURLConnection conn = (HttpURLConnection) url.openConnection(); conn.setReadTimeout(10000 /* milliseconds */); conn.setConnectTimeout(10000 /* milliseconds */); //conn.setRequestMethod("GET"); conn.setRequestProperty("Accept", "application/json"); conn.setRequestProperty("Authorization", authHeader); conn.setDoInput(true); conn.setDoOutput(false); conn.connect(); int response = conn.getResponseCode(); Log.d(TAG, "WarrantyCheck query responded: " + response); switch (response / 100) { case 2: is = conn.getInputStream(); RegistrationApiResponse.Reader reader = new RegistrationApiResponse.Reader(); result = reader.readJsonStream(is); break; case 4: case 5: is = conn.getErrorStream(); RegistrationApiErrorResponse.Reader errorReader = new RegistrationApiErrorResponse.Reader(); errorResult = errorReader.readErrorJsonStream(is); break; } } catch (UnsupportedEncodingException e) { e.printStackTrace(); return null; } catch (IOException e) { return null; } finally { if (is != null) { is.close(); } } return (result != null) ? result : errorResult; }
From source file:be.kuleuven.noiseapp.auth.AbstractGetInfoTask.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.//from ww w . j av a2s.co m * * @throws IOException * if communication with user info server failed. * @throws JSONException * if the response from the server could not be parsed. */ private UserDetails fetchInfoFromGoogleServer() throws IOException, JSONException { String token = fetchToken(); if (token == null) { // error has already been handled in fetchToken() return null; } 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(); String response = readResponse(is); JSONObject profile = new JSONObject(response); BigInteger googleID = getGoogleID(profile); String firstName = getFirstName(profile); String lastName = getLastName(profile); String pictureURL = getPicture(profile); is.close(); return new UserDetails(0L, googleID, firstName, lastName, mEmail, 0L, 0L, new ArrayList<Integer>(), null, pictureURL); } 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 null; } else { onError("Server returned the following error code: " + sc, null); Log.i(TAG, "Server auth error: " + readResponse(con.getErrorStream())); return null; } }
From source file:it.unipi.di.acube.batframework.systemPlugins.ERDSystem.java
@Override public HashSet<Tag> solveC2W(String text) throws AnnotationException { lastTime = Calendar.getInstance().getTimeInMillis(); HashSet<Tag> res = new HashSet<Tag>(); try {/* ww w.j a v a2s . c om*/ URL erdApi = new URL(url); HttpURLConnection connection = (HttpURLConnection) erdApi.openConnection(); connection.setDoOutput(true); connection.setRequestMethod("POST"); MultipartEntity multipartEntity = new MultipartEntity(HttpMultipartMode.STRICT); multipartEntity.addPart("runID", new StringBody(this.run)); multipartEntity.addPart("TextID", new StringBody("" + text.hashCode())); multipartEntity.addPart("Text", new StringBody(text)); connection.setRequestProperty("Content-Type", multipartEntity.getContentType().getValue()); OutputStream out = connection.getOutputStream(); try { multipartEntity.writeTo(out); } finally { out.close(); } int status = ((HttpURLConnection) connection).getResponseCode(); if (status != 200) { BufferedReader br = new BufferedReader(new InputStreamReader(connection.getErrorStream())); String line = null; while ((line = br.readLine()) != null) System.err.println(line); throw new RuntimeException(); } BufferedReader br = new BufferedReader(new InputStreamReader(connection.getInputStream())); String line = null; while ((line = br.readLine()) != null) { String mid = line.split("\t")[2]; String title = freebApi.midToTitle(mid); int wid; if (title == null || (wid = wikiApi.getIdByTitle(title)) == -1) System.err.println("Discarding mid=" + mid); else res.add(new Tag(wid)); } } catch (Exception e) { e.printStackTrace(); throw new RuntimeException(e); } lastTime = Calendar.getInstance().getTimeInMillis() - lastTime; return res; }
From source file:ccs_server.Sender.java
/** * Sends a message without retrying in case of service unavailability. See * {@link #send(Message, List, int)} for more info. * * @return multicast results if the message was sent successfully, * {@literal null} if it failed but could be retried. * * @throws IllegalArgumentException if registrationIds is {@literal null} or * empty./*from www . j ava 2 s . co m*/ * @throws InvalidRequestException if GCM didn't returned a 200 status. * @throws IOException if there was a JSON parsing error */ 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, 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()); jsonRequest.put(JSON_REGISTRATION_IDS, registrationIds); Map<String, String> payload = message.getData(); if (!payload.isEmpty()) { jsonRequest.put(JSON_PAYLOAD, payload); } String requestBody = JSONValue.toJSONString(jsonRequest); logger.finest("JSON request: " + requestBody); HttpURLConnection conn; int status; try { conn = post(GCM_SEND_ENDPOINT, "application/json", requestBody); status = conn.getResponseCode(); } catch (IOException e) { logger.log(Level.FINE, "IOException posting to GCM", e); return null; } String responseBody; if (status != 200) { try { responseBody = getAndClose(conn.getErrorStream()); logger.finest("JSON error response: " + responseBody); } catch (IOException e) { // ignore the exception since it will thrown an InvalidRequestException // anyways responseBody = "N/A"; logger.log(Level.FINE, "Exception reading response: ", e); } throw new InvalidRequestException(status, responseBody); } try { responseBody = getAndClose(conn.getInputStream()); } catch (IOException e) { logger.log(Level.WARNING, "IOException reading response", e); return null; } logger.finest("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); 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); 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:com.mabi87.httprequestbuilder.HTTPRequest.java
/** * @param connection//from ww w .j ava 2s .c o m * the HttpURLConnection of web server page. * @throws IOException * throws from HttpURLConnection method. * @return the HTTPResponse object */ private HTTPResponse readPage(HttpURLConnection connection) throws IOException { connection.connect(); int responseCode = connection.getResponseCode(); String lLine = null; String responseMessage = ""; try { BufferedReader messageReader = new BufferedReader(new InputStreamReader(connection.getInputStream())); StringBuilder messageBuilder = new StringBuilder(); while ((lLine = messageReader.readLine()) != null) { messageBuilder.append(lLine); messageBuilder.append('\n'); } messageReader.close(); responseMessage = messageBuilder.toString(); } catch (Exception e) { responseMessage = ""; } String errorMessage = ""; try { BufferedReader errorReader = new BufferedReader(new InputStreamReader(connection.getErrorStream())); StringBuilder errorBuilder = new StringBuilder(); while ((lLine = errorReader.readLine()) != null) { errorBuilder.append(lLine); errorBuilder.append('\n'); } errorReader.close(); errorMessage = errorBuilder.toString(); } catch (Exception e) { errorMessage = ""; } connection.disconnect(); return new HTTPResponse(responseCode, responseMessage, errorMessage); }
From source file:com.globallogic.push_service_poc.demo.sender.Sender.java
/** * Sends a message without retrying in case of service unavailability. See * {@link #send(Message, java.util.List, int)} for more info. * * @return multicast results if the message was sent successfully, * {@literal null} if it failed but could be retried. * * @throws IllegalArgumentException/*from w w w . j a va 2 s. c o m*/ * if registrationIds is {@literal null} or empty. * @throws InvalidRequestException * if GCM didn't returned a 200 status. * @throws java.io.IOException * if there was a JSON parsing error */ 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, 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()); jsonRequest.put(JSON_REGISTRATION_IDS, registrationIds); Map<String, String> payload = message.getData(); if (!payload.isEmpty()) { jsonRequest.put(JSON_PAYLOAD, payload); } String requestBody = JSONValue.toJSONString(jsonRequest); logger.finest("JSON request: " + requestBody); HttpURLConnection conn; int status; try { conn = post(GCM_SEND_ENDPOINT, "application/json", requestBody); status = conn.getResponseCode(); } catch (IOException e) { logger.log(Level.FINE, "IOException posting to GCM", e); return null; } String responseBody; if (status != 200) { try { responseBody = getAndClose(conn.getErrorStream()); logger.finest("JSON error response: " + responseBody); } catch (IOException e) { // ignore the exception since it will thrown an // InvalidRequestException // anyways responseBody = "N/A"; logger.log(Level.FINE, "Exception reading response: ", e); } throw new InvalidRequestException(status, responseBody); } try { responseBody = getAndClose(conn.getInputStream()); } catch (IOException e) { logger.log(Level.WARNING, "IOException reading response", e); return null; } logger.finest("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); 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); Result result = new 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:com.google.android.gcm.demo.sender.Sender.java
/** * Sends a message without retrying in case of service unavailability. See * {@link #send(Message, java.util.List, int)} for more info. * * @return multicast results if the message was sent successfully, * {@literal null} if it failed but could be retried. * * @throws IllegalArgumentException/*from w w w . j a va 2s.c om*/ * if registrationIds is {@literal null} or empty. * @throws InvalidRequestException * if GCM didn't returned a 200 status. * @throws java.io.IOException * if there was a JSON parsing error */ 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, 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()); jsonRequest.put(JSON_REGISTRATION_IDS, registrationIds); Map<String, String> payload = message.getData(); if (!payload.isEmpty()) { jsonRequest.put(JSON_PAYLOAD, payload); } String requestBody = JSONValue.toJSONString(jsonRequest); logger.finest("JSON request: " + requestBody); HttpURLConnection conn; int status; try { conn = post(GCM_SEND_ENDPOINT, "application/json", requestBody); status = conn.getResponseCode(); } catch (IOException e) { logger.log(Level.FINE, "IOException posting to GCM", e); return null; } String responseBody; if (status != 200) { try { responseBody = getAndClose(conn.getErrorStream()); logger.finest("JSON error response: " + responseBody); } catch (IOException e) { // ignore the exception since it will thrown an // InvalidRequestException // anyways responseBody = "N/A"; logger.log(Level.FINE, "Exception reading response: ", e); } throw new InvalidRequestException(status, responseBody); } try { responseBody = getAndClose(conn.getInputStream()); } catch (IOException e) { logger.log(Level.WARNING, "IOException reading response", e); return null; } logger.finest("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); 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); 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); } }