List of usage examples for java.net HttpURLConnection getResponseMessage
public String getResponseMessage() throws IOException
From source file:org.runnerup.export.EndomondoSynchronizer.java
@Override public Status upload(SQLiteDatabase db, long mID) { Status s;// w ww. j a v a 2 s. c o m if ((s = connect()) != Status.OK) { return s; } EndomondoTrack tcx = new EndomondoTrack(db); HttpURLConnection conn = null; Exception ex = null; try { EndomondoTrack.Summary summary = new EndomondoTrack.Summary(); StringWriter writer = new StringWriter(); tcx.export(mID, writer, summary); String workoutId = deviceId + "-" + Long.toString(mID); Log.e(getName(), "workoutId: " + workoutId); StringBuilder url = new StringBuilder(); url.append(UPLOAD_URL).append("?authToken=").append(authToken); url.append("&workoutId=").append(workoutId); url.append("&sport=").append(summary.sport); url.append("&duration=").append(summary.duration); url.append("&distance=").append(summary.distance); if (summary.hr != null) { url.append("&heartRateAvg=").append(summary.hr.toString()); } url.append("&gzip=true"); url.append("&extendedResponse=true"); conn = (HttpURLConnection) new URL(url.toString()).openConnection(); conn.setDoOutput(true); conn.setRequestMethod(RequestMethod.POST.name()); conn.addRequestProperty("Content-Type", "application/octet-stream"); OutputStream out = new GZIPOutputStream(new BufferedOutputStream(conn.getOutputStream())); out.write(writer.getBuffer().toString().getBytes()); out.flush(); out.close(); BufferedReader in = new BufferedReader(new InputStreamReader(conn.getInputStream())); JSONObject res = parseKVP(in); conn.disconnect(); Log.e(getName(), "res: " + res.toString()); int responseCode = conn.getResponseCode(); String amsg = conn.getResponseMessage(); if (responseCode == HttpStatus.SC_OK && "OK".contentEquals(res.getString("_0"))) { s.activityId = mID; return s; } ex = new Exception(amsg); } catch (IOException e) { ex = e; } catch (JSONException e) { ex = e; } s = Synchronizer.Status.ERROR; s.ex = ex; if (ex != null) { ex.printStackTrace(); } return s; }
From source file:de.mpg.escidoc.services.dataacquisition.DataHandlerBean.java
/** * Retrieves the content of a component from different escidoc instances. * // w ww . ja v a 2 s .com * @param identifier * @param url * @return content of a component as byte[] */ public byte[] retrieveComponentContent(String identifier, String url) { String coreservice = ""; URLConnection contentUrl; byte[] input = null; String sourceName = this.util.trimSourceName("escidoc", identifier); DataSourceVO source = this.sourceHandler.getSourceByName(sourceName); if (sourceName.equalsIgnoreCase("escidoc")) { try { coreservice = ServiceLocator.getFrameworkUrl(); } catch (Exception e) { this.logger.error("Framework Access threw an exception.", e); return null; } } if (sourceName.equalsIgnoreCase("escidocdev") || sourceName.equalsIgnoreCase("escidocqa") || sourceName.equalsIgnoreCase("escidocprod") || sourceName.equalsIgnoreCase("escidoctest")) { // escidoc source has only one dummy ft record FullTextVO ft = source.getFtFormats().get(0); coreservice = ft.getFtUrl().toString(); } try { contentUrl = ProxyHelper.openConnection(new URL(coreservice + url)); HttpURLConnection httpConn = (HttpURLConnection) contentUrl; int responseCode = httpConn.getResponseCode(); switch (responseCode) { case 503: // request was not processed by source this.logger.warn("Component content could not be fetched."); throw new RuntimeException("Component content could not be fetched. (503)"); case 200: this.logger.info("Source responded with 200."); GetMethod method = new GetMethod(coreservice + url); HttpClient client = new HttpClient(); ProxyHelper.executeMethod(client, method); input = method.getResponseBody(); httpConn.disconnect(); break; case 403: throw new AccessException("Access to component content is restricted."); default: throw new RuntimeException("An error occurred during importing from external system: " + responseCode + ": " + httpConn.getResponseMessage()); } } catch (Exception e) { this.logger.error("An error occurred while retrieving the item " + identifier + ".", e); throw new RuntimeException(e); } return input; }
From source file:de.mpg.escidoc.services.dataacquisition.DataHandlerBean.java
/** * Fetches a record via http protocol./*from w w w . j a v a 2 s . c o m*/ * * @param importSource * @param md * @return * @throws IdentifierNotRecognisedException * @throws RuntimeException * @throws AccessException */ private String fetchHttpRecord(MetadataVO md) throws IdentifierNotRecognisedException, RuntimeException, AccessException { String item = ""; URLConnection conn; String charset = this.currentSource.getEncoding(); InputStreamReader isReader; BufferedReader bReader; try { conn = ProxyHelper.openConnection(md.getMdUrl()); HttpURLConnection httpConn = (HttpURLConnection) conn; int responseCode = httpConn.getResponseCode(); switch (responseCode) { case 503: // request was not processed by source this.logger.warn("Import source " + this.currentSource.getName() + "did not provide file."); throw new FormatNotAvailableException(md.getMdLabel()); case 302: String alternativeLocation = conn.getHeaderField("Location"); md.setMdUrl(new URL(alternativeLocation)); this.currentSource = this.sourceHandler.updateMdEntry(this.currentSource, md); return fetchHttpRecord(md); case 200: this.logger.info("Source responded with 200"); break; case 403: throw new AccessException("Access to url " + this.currentSource.getName() + " is restricted."); default: throw new RuntimeException("An error occurred during importing from external system: " + responseCode + ": " + httpConn.getResponseMessage()); } // Get itemXML isReader = new InputStreamReader(md.getMdUrl().openStream(), charset); bReader = new BufferedReader(isReader); String line = ""; while ((line = bReader.readLine()) != null) { item += line + "\n"; } httpConn.disconnect(); } catch (AccessException e) { this.logger.error("Access denied.", e); throw new AccessException(this.currentSource.getName()); } catch (Exception e) { throw new RuntimeException(e); } return item; }
From source file:net.myrrix.client.ClientRecommender.java
private int getNumClusters(boolean user) throws TasteException { String urlPath = '/' + (user ? "user" : "item") + "/clusters/count"; TasteException savedException = null; for (HostAndPort replica : choosePartitionAndReplicas(0L)) { HttpURLConnection connection = null; try {//from w w w. j av a 2s .c o m connection = buildConnectionToReplica(replica, urlPath, "GET"); switch (connection.getResponseCode()) { case HttpURLConnection.HTTP_OK: BufferedReader reader = IOUtils.bufferStream(connection.getInputStream()); try { return Integer.parseInt(reader.readLine()); } finally { reader.close(); } case HttpURLConnection.HTTP_NOT_IMPLEMENTED: throw new UnsupportedOperationException(); case HttpURLConnection.HTTP_UNAVAILABLE: throw new NotReadyException(); default: throw new TasteException(connection.getResponseCode() + " " + connection.getResponseMessage()); } } catch (TasteException te) { log.info("Can't access {} at {}: ({})", urlPath, replica, te.toString()); savedException = te; } catch (IOException ioe) { log.info("Can't access {} at {}: ({})", urlPath, replica, ioe.toString()); savedException = new TasteException(ioe); } finally { if (connection != null) { connection.disconnect(); } } } throw savedException; }
From source file:net.myrrix.client.ClientRecommender.java
/** * Like {@link #similarityToItem(long, long[])}, but allows caller to specify the user for which the request * is being made. This information does not directly affect the computation, but affects <em>routing</em> * of the request in a distributed context. This is always recommended when there is a user in whose context * the request is being made, as it will ensure that the request can take into account all the latest information * from the user, including very new items that may be in {@code itemIDs}. */// w w w . j a v a 2 s.co m public float[] similarityToItem(long toItemID, long[] itemIDs, Long contextUserID) throws TasteException { StringBuilder urlPath = new StringBuilder(32); urlPath.append("/similarityToItem/"); urlPath.append(toItemID); for (long itemID : itemIDs) { urlPath.append('/').append(itemID); } // Requests are typically partitioned by user, but this request does not directly depend on a user. // If a user ID is supplied anyway, use it for partitioning since it will follow routing for other // requests related to that user. Otherwise just partition on (first0 item ID, which is at least // deterministic. long idToPartitionOn = contextUserID == null ? itemIDs[0] : contextUserID; TasteException savedException = null; for (HostAndPort replica : choosePartitionAndReplicas(idToPartitionOn)) { HttpURLConnection connection = null; try { connection = buildConnectionToReplica(replica, urlPath.toString(), "GET"); switch (connection.getResponseCode()) { case HttpURLConnection.HTTP_OK: BufferedReader reader = IOUtils.bufferStream(connection.getInputStream()); try { float[] result = new float[itemIDs.length]; for (int i = 0; i < itemIDs.length; i++) { result[i] = LangUtils.parseFloat(reader.readLine()); } return result; } finally { reader.close(); } case HttpURLConnection.HTTP_NOT_FOUND: throw new NoSuchItemException(connection.getResponseMessage()); case HttpURLConnection.HTTP_UNAVAILABLE: throw new NotReadyException(); default: throw new TasteException(connection.getResponseCode() + " " + connection.getResponseMessage()); } } catch (TasteException te) { log.info("Can't access {} at {}: ({})", urlPath, replica, te.toString()); savedException = te; } catch (IOException ioe) { log.info("Can't access {} at {}: ({})", urlPath, replica, ioe.toString()); savedException = new TasteException(ioe); } finally { if (connection != null) { connection.disconnect(); } } } throw savedException; }
From source file:com.apptentive.android.sdk.comm.ApptentiveClient.java
private static ApptentiveHttpResponse performMultipartFilePost(Context context, String oauthToken, String uri, String postBody, StoredFile storedFile) { Log.d("Performing multipart request to %s", uri); ApptentiveHttpResponse ret = new ApptentiveHttpResponse(); if (storedFile == null) { Log.e("StoredFile is null. Unable to send."); return ret; }/* w w w. jav a 2 s . c om*/ int bytesRead; int bufferSize = 4096; byte[] buffer; String lineEnd = "\r\n"; String twoHyphens = "--"; String boundary = UUID.randomUUID().toString(); HttpURLConnection connection; DataOutputStream os = null; InputStream is = null; try { is = context.openFileInput(storedFile.getLocalFilePath()); // Set up the request. URL url = new URL(uri); connection = (HttpURLConnection) url.openConnection(); connection.setDoInput(true); connection.setDoOutput(true); connection.setUseCaches(false); connection.setConnectTimeout(DEFAULT_HTTP_CONNECT_TIMEOUT); connection.setReadTimeout(DEFAULT_HTTP_SOCKET_TIMEOUT); connection.setRequestMethod("POST"); connection.setRequestProperty("Connection", "Keep-Alive"); connection.setRequestProperty("Content-Type", "multipart/form-data;boundary=" + boundary); connection.setRequestProperty("Authorization", "OAuth " + oauthToken); connection.setRequestProperty("Accept", "application/json"); connection.setRequestProperty("X-API-Version", API_VERSION); connection.setRequestProperty("User-Agent", getUserAgentString()); StringBuilder requestText = new StringBuilder(); // Write form data requestText.append(twoHyphens).append(boundary).append(lineEnd); requestText.append("Content-Disposition: form-data; name=\"message\"").append(lineEnd); requestText.append("Content-Type: text/plain").append(lineEnd); requestText.append(lineEnd); requestText.append(postBody); requestText.append(lineEnd); // Write file attributes. requestText.append(twoHyphens).append(boundary).append(lineEnd); requestText.append(String.format("Content-Disposition: form-data; name=\"file\"; filename=\"%s\"", storedFile.getFileName())).append(lineEnd); requestText.append("Content-Type: ").append(storedFile.getMimeType()).append(lineEnd); requestText.append(lineEnd); Log.d("Post body: " + requestText); // Open an output stream. os = new DataOutputStream(connection.getOutputStream()); // Write the text so far. os.writeBytes(requestText.toString()); try { // Write the actual file. buffer = new byte[bufferSize]; while ((bytesRead = is.read(buffer, 0, bufferSize)) > 0) { os.write(buffer, 0, bytesRead); } } catch (IOException e) { Log.d("Error writing file bytes to HTTP connection.", e); ret.setBadPayload(true); throw e; } os.writeBytes(twoHyphens + boundary + twoHyphens + lineEnd); os.close(); ret.setCode(connection.getResponseCode()); ret.setReason(connection.getResponseMessage()); // TODO: These streams may not be ready to read now. Put this in a new thread. // Read the normal response. InputStream nis = null; ByteArrayOutputStream nbaos = null; try { Log.d("Sending file: " + storedFile.getLocalFilePath()); nis = connection.getInputStream(); nbaos = new ByteArrayOutputStream(); byte[] eBuf = new byte[1024]; int eRead; while (nis != null && (eRead = nis.read(eBuf, 0, 1024)) > 0) { nbaos.write(eBuf, 0, eRead); } ret.setContent(nbaos.toString()); } catch (IOException e) { Log.w("Can't read return stream.", e); } finally { Util.ensureClosed(nis); Util.ensureClosed(nbaos); } // Read the error response. InputStream eis = null; ByteArrayOutputStream ebaos = null; try { eis = connection.getErrorStream(); ebaos = new ByteArrayOutputStream(); byte[] eBuf = new byte[1024]; int eRead; while (eis != null && (eRead = eis.read(eBuf, 0, 1024)) > 0) { ebaos.write(eBuf, 0, eRead); } if (ebaos.size() > 0) { ret.setContent(ebaos.toString()); } } catch (IOException e) { Log.w("Can't read error stream.", e); } finally { Util.ensureClosed(eis); Util.ensureClosed(ebaos); } Log.d("HTTP " + connection.getResponseCode() + ": " + connection.getResponseMessage() + ""); Log.v(ret.getContent()); } catch (FileNotFoundException e) { Log.e("Error getting file to upload.", e); } catch (MalformedURLException e) { Log.e("Error constructing url for file upload.", e); } catch (SocketTimeoutException e) { Log.w("Timeout communicating with server."); } catch (IOException e) { Log.e("Error executing file upload.", e); } finally { Util.ensureClosed(is); Util.ensureClosed(os); } return ret; }
From source file:net.myrrix.client.ClientRecommender.java
public float estimateForAnonymous(long toItemID, long[] itemIDs, float[] values, Long contextUserID) throws TasteException { Preconditions.checkArgument(values == null || values.length == itemIDs.length, "Number of values doesn't match number of items"); StringBuilder urlPath = new StringBuilder(32); urlPath.append("/estimateForAnonymous/"); urlPath.append(toItemID);// w w w .jav a 2 s.c om for (int i = 0; i < itemIDs.length; i++) { urlPath.append('/').append(itemIDs[i]); if (values != null) { urlPath.append('=').append(values[i]); } } // Requests are typically partitioned by user, but this request does not directly depend on a user. // If a user ID is supplied anyway, use it for partitioning since it will follow routing for other // requests related to that user. Otherwise just partition on the "to" item ID, which is at least // deterministic. long idToPartitionOn = contextUserID == null ? toItemID : contextUserID; TasteException savedException = null; for (HostAndPort replica : choosePartitionAndReplicas(idToPartitionOn)) { HttpURLConnection connection = null; try { connection = buildConnectionToReplica(replica, urlPath.toString(), "GET"); switch (connection.getResponseCode()) { case HttpURLConnection.HTTP_OK: BufferedReader reader = IOUtils.bufferStream(connection.getInputStream()); try { return LangUtils.parseFloat(reader.readLine()); } finally { reader.close(); } case HttpURLConnection.HTTP_NOT_FOUND: throw new NoSuchItemException(Arrays.toString(itemIDs) + ' ' + toItemID); case HttpURLConnection.HTTP_UNAVAILABLE: throw new NotReadyException(); default: throw new TasteException(connection.getResponseCode() + " " + connection.getResponseMessage()); } } catch (TasteException te) { log.info("Can't access {} at {}: ({})", urlPath, replica, te.toString()); savedException = te; } catch (IOException ioe) { log.info("Can't access {} at {}: ({})", urlPath, replica, ioe.toString()); savedException = new TasteException(ioe); } finally { if (connection != null) { connection.disconnect(); } } } throw savedException; }
From source file:com.heliosdecompiler.bootstrapper.Bootstrapper.java
private static void forceUpdate() throws IOException, VcdiffDecodeException { File backupFile = new File(DATA_DIR, "helios.jar.bak"); try {// w w w . j a v a2s .c om Files.copy(IMPL_FILE.toPath(), backupFile.toPath(), StandardCopyOption.REPLACE_EXISTING); } catch (IOException exception) { // We're going to wrap it so end users know what went wrong throw new IOException(String.format("Could not back up Helios implementation (%s %s, %s %s)", IMPL_FILE.canRead(), IMPL_FILE.canWrite(), backupFile.canRead(), backupFile.canWrite()), exception); } URL latestVersion = new URL("https://ci.samczsun.com/job/Helios/lastStableBuild/buildNumber"); HttpURLConnection connection = (HttpURLConnection) latestVersion.openConnection(); if (connection.getResponseCode() == 200) { boolean aborted = false; ByteArrayOutputStream outputStream = new ByteArrayOutputStream(); copy(connection.getInputStream(), outputStream); String version = new String(outputStream.toByteArray(), "UTF-8"); System.out.println("Latest version: " + version); int intVersion = Integer.parseInt(version); loop: while (true) { int buildNumber = loadHelios().buildNumber; int oldBuildNumber = buildNumber; System.out.println("Current Helios version is " + buildNumber); if (buildNumber < intVersion) { while (buildNumber <= intVersion) { buildNumber++; URL status = new URL("https://ci.samczsun.com/job/Helios/" + buildNumber + "/api/json"); HttpURLConnection con = (HttpURLConnection) status.openConnection(); if (con.getResponseCode() == 200) { JsonObject object = Json.parse(new InputStreamReader(con.getInputStream())).asObject(); if (object.get("result").asString().equals("SUCCESS")) { JsonArray artifacts = object.get("artifacts").asArray(); for (JsonValue value : artifacts.values()) { JsonObject artifact = value.asObject(); String name = artifact.get("fileName").asString(); if (name.contains("helios-") && !name.contains(IMPLEMENTATION_VERSION)) { JOptionPane.showMessageDialog(null, "Bootstrapper is out of date. Patching cannot continue"); aborted = true; break loop; } } URL url = new URL("https://ci.samczsun.com/job/Helios/" + buildNumber + "/artifact/target/delta.patch"); con = (HttpURLConnection) url.openConnection(); if (con.getResponseCode() == 200) { File dest = new File(DATA_DIR, "delta.patch"); ByteArrayOutputStream byteArrayOutputStream = new ByteArrayOutputStream(); copy(con.getInputStream(), byteArrayOutputStream); FileOutputStream fileOutputStream = new FileOutputStream(dest); fileOutputStream.write(byteArrayOutputStream.toByteArray()); fileOutputStream.close(); File cur = IMPL_FILE; File old = new File(IMPL_FILE.getAbsolutePath() + "." + oldBuildNumber); if (cur.renameTo(old)) { VcdiffDecoder.decode(old, dest, cur); old.delete(); dest.delete(); continue loop; } else { throw new IllegalArgumentException("Could not rename"); } } } } else { JOptionPane.showMessageDialog(null, "Server returned response code " + con.getResponseCode() + " " + con.getResponseMessage() + "\nAborting patch process", null, JOptionPane.INFORMATION_MESSAGE); aborted = true; break loop; } } } else { break; } } if (!aborted) { int buildNumber = loadHelios().buildNumber; System.out.println("Running Helios version " + buildNumber); JOptionPane.showMessageDialog(null, "Updated Helios to version " + buildNumber + "!"); Runtime.getRuntime().exec(new String[] { "java", "-jar", BOOTSTRAPPER_FILE.getAbsolutePath() }); } else { try { Files.copy(backupFile.toPath(), IMPL_FILE.toPath(), StandardCopyOption.REPLACE_EXISTING); } catch (IOException exception) { // We're going to wrap it so end users know what went wrong throw new IOException("Critical Error! Could not restore Helios implementation to original copy" + "Try relaunching the Bootstrapper. If that doesn't work open a GitHub issue with details", exception); } } System.exit(0); } else { throw new IOException(connection.getResponseCode() + ": " + connection.getResponseMessage()); } }
From source file:net.reichholf.dreamdroid.helpers.SimpleHttpClient.java
/** * @param uri/* w ww . j a v a 2 s. co m*/ * @param parameters * @return */ public boolean fetchPageContent(String uri, List<NameValuePair> parameters) { // Set login, ssl, port, host etc; applyConfig(); mErrorText = ""; mErrorTextId = -1; mError = false; mBytes = new byte[0]; if (!uri.startsWith("/")) { uri = "/".concat(uri); } HttpURLConnection conn = null; try { if (mProfile.getSessionId() != null) parameters.add(new BasicNameValuePair("sessionid", mProfile.getSessionId())); URL url = new URL(buildUrl(uri, parameters)); conn = (HttpURLConnection) url.openConnection(); conn.setConnectTimeout(mConnectionTimeoutMillis); if (DreamDroid.featurePostRequest()) conn.setRequestMethod("POST"); setAuth(conn); if (conn.getResponseCode() != 200) { if (conn.getResponseCode() == HttpURLConnection.HTTP_BAD_METHOD && mRememberedReturnCode != HttpURLConnection.HTTP_BAD_METHOD) { // Method not allowed, the target device either can't handle // POST or GET requests (old device or Anti-Hijack enabled) DreamDroid.setFeaturePostRequest(!DreamDroid.featurePostRequest()); conn.disconnect(); mRememberedReturnCode = HttpURLConnection.HTTP_BAD_METHOD; return fetchPageContent(uri, parameters); } if (conn.getResponseCode() == HttpURLConnection.HTTP_PRECON_FAILED && mRememberedReturnCode != HttpURLConnection.HTTP_PRECON_FAILED) { createSession(); conn.disconnect(); mRememberedReturnCode = HttpURLConnection.HTTP_PRECON_FAILED; return fetchPageContent(uri, parameters); } mRememberedReturnCode = 0; Log.e(LOG_TAG, Integer.toString(conn.getResponseCode())); switch (conn.getResponseCode()) { case HttpURLConnection.HTTP_UNAUTHORIZED: mErrorTextId = R.string.auth_error; break; default: mErrorTextId = -1; } mErrorText = conn.getResponseMessage(); mError = true; return false; } BufferedInputStream bis = new BufferedInputStream(conn.getInputStream()); ByteArrayBuffer baf = new ByteArrayBuffer(50); int read = 0; int bufSize = 512; byte[] buffer = new byte[bufSize]; while ((read = bis.read(buffer)) != -1) { baf.append(buffer, 0, read); } mBytes = baf.toByteArray(); if (DreamDroid.dumpXml()) dumpToFile(url); return true; } catch (MalformedURLException e) { mError = true; mErrorTextId = R.string.illegal_host; } catch (UnknownHostException e) { mError = true; mErrorText = null; mErrorTextId = R.string.host_not_found; } catch (ProtocolException e) { mError = true; mErrorText = e.getLocalizedMessage(); } catch (ConnectException e) { mError = true; mErrorTextId = R.string.host_unreach; } catch (IOException e) { e.printStackTrace(); mError = true; mErrorText = e.getLocalizedMessage(); } finally { if (conn != null) conn.disconnect(); if (mError) if (mErrorText == null) mErrorText = "Error text is null"; Log.e(LOG_TAG, mErrorText); } return false; }
From source file:fi.cosky.sdk.API.java
private <T extends BaseData> T sendRequestWithAddedHeaders(Verb verb, String url, Class<T> tClass, Object object, HashMap<String, String> headers) throws IOException { URL serverAddress;//from w w w . ja v a 2s . c om HttpURLConnection connection; BufferedReader br; String result = ""; try { serverAddress = new URL(url); connection = (HttpURLConnection) serverAddress.openConnection(); connection.setInstanceFollowRedirects(false); boolean doOutput = doOutput(verb); connection.setDoOutput(doOutput); connection.setRequestMethod(method(verb)); connection.setRequestProperty("Authorization", headers.get("authorization")); connection.addRequestProperty("Accept", "application/json"); if (doOutput) { connection.addRequestProperty("Content-Length", "0"); OutputStreamWriter os = new OutputStreamWriter(connection.getOutputStream()); os.write(""); os.flush(); os.close(); } connection.connect(); if (connection.getResponseCode() == HttpURLConnection.HTTP_SEE_OTHER || connection.getResponseCode() == HttpURLConnection.HTTP_CREATED) { Link location = parseLocationLinkFromString(connection.getHeaderField("Location")); Link l = new Link("self", "/tokens", "GET", "", true); ArrayList<Link> links = new ArrayList<Link>(); links.add(l); links.add(location); ResponseData data = new ResponseData(); data.setLocation(location); data.setLinks(links); return (T) data; } if (connection.getResponseCode() == HttpURLConnection.HTTP_UNAUTHORIZED) { System.out.println("Authentication expired: " + connection.getResponseMessage()); if (retry && this.tokenData != null) { retry = false; this.tokenData = null; if (authenticate()) { System.out.println( "Reauthentication success, will continue with " + verb + " request on " + url); return sendRequestWithAddedHeaders(verb, url, tClass, object, headers); } } else throw new IOException( "Tried to reauthenticate but failed, please check the credentials and status of NFleet-API"); } if (connection.getResponseCode() >= HttpURLConnection.HTTP_BAD_REQUEST && connection.getResponseCode() < HttpURLConnection.HTTP_INTERNAL_ERROR) { System.out.println("ErrorCode: " + connection.getResponseCode() + " " + connection.getResponseMessage() + " " + url + ", verb: " + verb); String errorString = readErrorStreamAndCloseConnection(connection); throw (NFleetRequestException) gson.fromJson(errorString, NFleetRequestException.class); } else if (connection.getResponseCode() >= HttpURLConnection.HTTP_INTERNAL_ERROR) { if (retry) { System.out.println("Server responded with internal server error, trying again in " + RETRY_WAIT_TIME + " msec."); try { retry = false; Thread.sleep(RETRY_WAIT_TIME); return sendRequestWithAddedHeaders(verb, url, tClass, object, headers); } catch (InterruptedException e) { } } else { System.out.println("Server responded with internal server error, please contact dev@nfleet.fi"); } String errorString = readErrorStreamAndCloseConnection(connection); throw new IOException(errorString); } result = readDataFromConnection(connection); } catch (MalformedURLException e) { throw e; } catch (ProtocolException e) { throw e; } catch (UnsupportedEncodingException e) { throw e; } catch (IOException e) { throw e; } return (T) gson.fromJson(result, tClass); }