List of usage examples for java.net HttpURLConnection getResponseCode
public int getResponseCode() throws IOException
From source file:com.createtank.payments.coinbase.RequestClient.java
private static JsonObject call(CoinbaseApi api, String method, RequestVerb verb, JsonObject json, boolean retry, String accessToken) throws IOException, UnsupportedRequestVerbException { if (verb == RequestVerb.DELETE || verb == RequestVerb.GET) { throw new UnsupportedRequestVerbException(); }/*from w ww . j av a2 s. c om*/ if (api.allowSecure()) { HttpClient client = HttpClientBuilder.create().build(); String url = BASE_URL + method; HttpUriRequest request; switch (verb) { case POST: request = new HttpPost(url); break; case PUT: request = new HttpPut(url); break; default: throw new RuntimeException("RequestVerb not implemented: " + verb); } ((HttpEntityEnclosingRequestBase) request) .setEntity(new StringEntity(json.toString(), ContentType.APPLICATION_JSON)); if (accessToken != null) request.addHeader("Authorization", String.format("Bearer %s", accessToken)); request.addHeader("Content-Type", "application/json"); HttpResponse response = client.execute(request); int code = response.getStatusLine().getStatusCode(); if (code == 401) { if (retry) { api.refreshAccessToken(); call(api, method, verb, json, false, api.getAccessToken()); } else { throw new IOException("Account is no longer valid"); } } else if (code != 200) { throw new IOException("HTTP response " + code + " to request " + method); } String responseString = EntityUtils.toString(response.getEntity()); if (responseString.startsWith("[")) { // Is an array responseString = "{response:" + responseString + "}"; } JsonParser parser = new JsonParser(); JsonObject resp = (JsonObject) parser.parse(responseString); System.out.println(resp.toString()); return resp; } String url = BASE_URL + method; HttpURLConnection conn = (HttpURLConnection) new URL(url).openConnection(); conn.setRequestMethod(verb.name()); conn.addRequestProperty("Content-Type", "application/json"); if (accessToken != null) conn.setRequestProperty("Authorization", String.format("Bearer %s", accessToken)); conn.setDoOutput(true); OutputStreamWriter writer = new OutputStreamWriter(conn.getOutputStream()); writer.write(json.toString()); writer.flush(); writer.close(); int code = conn.getResponseCode(); if (code == 401) { if (retry) { api.refreshAccessToken(); return call(api, method, verb, json, false, api.getAccessToken()); } else { throw new IOException("Account is no longer valid"); } } else if (code != 200) { throw new IOException("HTTP response " + code + " to request " + method); } String responseString = getResponseBody(conn.getInputStream()); if (responseString.startsWith("[")) { responseString = "{response:" + responseString + "}"; } JsonParser parser = new JsonParser(); return (JsonObject) parser.parse(responseString); }
From source file:edu.stanford.epadd.launcher.Splash.java
private static boolean isURLAlive(String url) throws IOException { try {/*from w w w. ja va 2 s . co m*/ // attempt to fetch the page // throws a connect exception if the server is not even running // so catch it and return false // since "index" may auto load default archive, attach it to session, and redirect to "info" page, // we need to maintain the session across the pages. // see "Maintaining the session" at http://stackoverflow.com/questions/2793150/how-to-use-java-net-urlconnection-to-fire-and-handle-http-requests CookieHandler.setDefault(new CookieManager(null, CookiePolicy.ACCEPT_ALL)); out.println("Testing for already running ePADD by probing " + url); System.out.println("Testing for already running ePADD by probing " + url); HttpURLConnection u = (HttpURLConnection) new URL(url).openConnection(); if (u.getResponseCode() == 200) { u.disconnect(); out.println("ePADD is already running!"); return true; } u.disconnect(); } catch (ConnectException ce) { } out.println("Good, ePADD is not already running"); return false; }
From source file:dlauncher.authorization.DefaultCredentialsManager.java
private static JSONObject makeRequest(URL url, JSONObject post, boolean ignoreErrors) throws ProtocolException, IOException, AuthorizationException { JSONObject obj = null;//www . j a va2s . c om try { HttpURLConnection con = (HttpURLConnection) url.openConnection(); con.setDoOutput(true); con.setDoInput(true); con.setUseCaches(false); con.setRequestMethod("POST"); con.setRequestProperty("Content-Type", "application/json"); con.setConnectTimeout(15 * 1000); con.setReadTimeout(15 * 1000); con.connect(); try (OutputStream out = con.getOutputStream()) { out.write(post.toString().getBytes(Charset.forName("UTF-8"))); } con.getResponseCode(); InputStream instr; instr = con.getErrorStream(); if (instr == null) { instr = con.getInputStream(); } byte[] data = new byte[1024]; int length; try (SizeLimitedByteArrayOutputStream bytes = new SizeLimitedByteArrayOutputStream(1024 * 4)) { try (InputStream in = new BufferedInputStream(instr)) { while ((length = in.read(data)) >= 0) { bytes.write(data, 0, length); } } byte[] rawBytes = bytes.toByteArray(); if (rawBytes.length != 0) { obj = new JSONObject(new String(rawBytes, Charset.forName("UTF-8"))); } else { obj = new JSONObject(); } if (!ignoreErrors && obj.has("error")) { String error = obj.getString("error"); String errorMessage = obj.getString("errorMessage"); String cause = obj.optString("cause", null); if ("ForbiddenOperationException".equals(error)) { if ("UserMigratedException".equals(cause)) { throw new UserMigratedException(errorMessage); } throw new ForbiddenOperationException(errorMessage); } throw new AuthorizationException( error + (cause != null ? "." + cause : "") + ": " + errorMessage); } return obj; } } catch (JSONException ex) { throw new InvalidResponseException(ex, obj); } }
From source file:edu.stanford.epadd.launcher.Splash.java
private static boolean killRunningServer(String url) throws IOException { try {//from w ww . ja va 2s . c om // attempt to fetch the page // throws a connect exception if the server is not even running // so catch it and return false String http = url + "/exit.jsp?message=Shutdown%20request%20from%20a%20different%20instance%20of%20ePADD"; // version num spaces and brackets screw up the URL connection out.println("Sending a kill request to " + http); HttpURLConnection u = (HttpURLConnection) new URL(http).openConnection(); u.connect(); if (u.getResponseCode() == 200) { u.disconnect(); return true; } u.disconnect(); } catch (ConnectException ce) { } return false; }
From source file:de.ipbhalle.metfrag.pubchem.PubChemWebService.java
/** * /*from www .ja va 2 s. c o m*/ * @author c-ruttkies * * @param urlname * @return */ private static InputStream getInputStreamFromURL(String urlname) { InputStream stream = null; try { URL url = new URL(urlname); HttpURLConnection conn = (HttpURLConnection) url.openConnection(); if (conn.getResponseCode() != 200) { throw new IOException(conn.getResponseMessage()); } stream = conn.getInputStream(); } catch (MalformedURLException mue) { System.err.println("Error: Could create URL object!"); System.exit(1); } catch (IOException e) { System.err.println("Error: Could not open URL connection!"); System.exit(2); } return stream; }
From source file:com.adr.raspberryleds.HTTPUtils.java
public static JSONObject execPOST(String address, JSONObject params) throws IOException { BufferedReader readerin = null; Writer writerout = null;/* w w w .j a va 2 s. c o m*/ try { URL url = new URL(address); String query = params.toString(); HttpURLConnection connection = (HttpURLConnection) url.openConnection(); connection.setReadTimeout(10000 /* milliseconds */); connection.setConnectTimeout(15000 /* milliseconds */); connection.setRequestMethod("POST"); connection.setAllowUserInteraction(false); connection.setUseCaches(false); connection.setDoInput(true); connection.setDoOutput(true); connection.addRequestProperty("Content-Type", "application/json,encoding=UTF-8"); connection.addRequestProperty("Content-length", String.valueOf(query.length())); writerout = new OutputStreamWriter(connection.getOutputStream(), "UTF-8"); writerout.write(query); writerout.flush(); writerout.close(); writerout = null; int responsecode = connection.getResponseCode(); if (responsecode == HttpURLConnection.HTTP_OK) { StringBuilder text = new StringBuilder(); readerin = new BufferedReader(new InputStreamReader(connection.getInputStream(), "UTF-8")); String line = null; while ((line = readerin.readLine()) != null) { text.append(line); text.append(System.getProperty("line.separator")); } JSONObject result = new JSONObject(text.toString()); if (result.has("exception")) { throw new IOException( MessageFormat.format("Remote exception: {0}.", result.getString("exception"))); } else { return result; } } else { throw new IOException(MessageFormat.format("HTTP response error: {0}. {1}", Integer.toString(responsecode), connection.getResponseMessage())); } } catch (JSONException ex) { throw new IOException(MessageFormat.format("Parse exception: {0}.", ex.getMessage())); } finally { if (writerout != null) { writerout.close(); writerout = null; } if (readerin != null) { readerin.close(); readerin = null; } } }
From source file:com.moviejukebox.plugin.OpenSubtitlesPlugin.java
private static boolean subtitleDownload(Movie movie, File movieFile, File subtitleFile) { try {/*from ww w. j ava2 s . co m*/ String ret; String xml; String moviehash = getHash(movieFile); String moviebytesize = String.valueOf(movieFile.length()); xml = generateXMLRPCSS(moviehash, moviebytesize); ret = sendRPC(xml); String subDownloadLink = getValue("SubDownloadLink", ret); if (StringUtils.isBlank(subDownloadLink)) { String moviefilename = movieFile.getName(); // Do not search by file name for BD rip files in the format 0xxxx.m2ts if (!(moviefilename.toUpperCase().endsWith(".M2TS") && moviefilename.startsWith("0"))) { // Try to find the subtitle using file name String subfilename = subtitleFile.getName(); int index = subfilename.lastIndexOf('.'); String query = subfilename.substring(0, index); xml = generateXMLRPCSS(query); ret = sendRPC(xml); subDownloadLink = getValue("SubDownloadLink", ret); } } if (StringUtils.isBlank(subDownloadLink)) { LOG.debug("Subtitle not found for {}", movieFile.getName()); return Boolean.FALSE; } LOG.debug("Download subtitle for {}", movie.getBaseName()); URL url = new URL(subDownloadLink); HttpURLConnection connection = (HttpURLConnection) (url .openConnection(YamjHttpClientBuilder.getProxy())); connection.setRequestProperty("Connection", "Close"); try (InputStream inputStream = connection.getInputStream()) { int code = connection.getResponseCode(); if (code != HttpURLConnection.HTTP_OK) { LOG.error("Download Failed"); return Boolean.FALSE; } FileTools.copy(inputStream, new FileOutputStream(subtitleFile)); } finally { connection.disconnect(); } String subLanguageID = getValue("SubLanguageID", ret); if (StringUtils.isNotBlank(subLanguageID)) { SubtitleTools.addMovieSubtitle(movie, subLanguageID); } else { SubtitleTools.addMovieSubtitle(movie, "YES"); } return Boolean.TRUE; } catch (Exception ex) { LOG.error("Download Exception (Movie Not Found)", ex); return Boolean.FALSE; } }
From source file:com.vaguehope.onosendai.util.HttpHelper.java
private static <R> R fetchWithFollowRedirects(final Method method, final URL url, final HttpStreamHandler<R> streamHandler, final int redirectCount) throws IOException, URISyntaxException { final HttpURLConnection connection = (HttpURLConnection) url.openConnection(); try {/* ww w .ja va 2 s . c o m*/ connection.setRequestMethod(method.toString()); connection.setInstanceFollowRedirects(false); connection.setConnectTimeout((int) TimeUnit.SECONDS.toMillis(HTTP_CONNECT_TIMEOUT_SECONDS)); connection.setReadTimeout((int) TimeUnit.SECONDS.toMillis(HTTP_READ_TIMEOUT_SECONDS)); connection.setRequestProperty("User-Agent", "curl/1"); // Make it really clear this is not a browser. //connection.setRequestProperty("Accept-Encoding", "identity"); This fixes missing Content-Length headers but feels wrong. connection.connect(); InputStream is = null; try { final int responseCode = connection.getResponseCode(); // For some reason some devices do not follow redirects. :( if (responseCode == 301 || responseCode == 302 || responseCode == 303 || responseCode == 307) { // NOSONAR not magic numbers. Its HTTP spec. if (redirectCount >= MAX_REDIRECTS) throw new TooManyRedirectsException(responseCode, url, MAX_REDIRECTS); final String locationHeader = connection.getHeaderField("Location"); if (locationHeader == null) throw new HttpResponseException(responseCode, "Location header missing. Headers present: " + connection.getHeaderFields() + "."); connection.disconnect(); final URL locationUrl; if (locationHeader.toLowerCase(Locale.ENGLISH).startsWith("http")) { locationUrl = new URL(locationHeader); } else { locationUrl = url.toURI().resolve(locationHeader).toURL(); } return fetchWithFollowRedirects(method, locationUrl, streamHandler, redirectCount + 1); } if (responseCode < 200 || responseCode >= 300) { // NOSONAR not magic numbers. Its HTTP spec. throw new NotOkResponseException(responseCode, connection, url); } is = connection.getInputStream(); final int contentLength = connection.getContentLength(); if (contentLength < 1) LOG.w("Content-Length=%s for %s.", contentLength, url); return streamHandler.handleStream(connection, is, contentLength); } finally { IoHelper.closeQuietly(is); } } finally { connection.disconnect(); } }
From source file:com.github.codingtogenomic.CodingToGenomic.java
private static String getContent(final String endpoint) throws MalformedURLException, IOException, InterruptedException { if (requestCount == 15) { // check every 15 final long currentTime = System.currentTimeMillis(); final long diff = currentTime - lastRequestTime; //if less than a second then sleep for the remainder of the second if (diff < 1000) { Thread.sleep(1000 - diff); }/*from www. j av a 2s . c om*/ //reset lastRequestTime = System.currentTimeMillis(); requestCount = 0; } final URL url = new URL(SERVER + endpoint); URLConnection connection = url.openConnection(); HttpURLConnection httpConnection = (HttpURLConnection) connection; httpConnection.setRequestProperty("Content-Type", "application/json"); final InputStream response = httpConnection.getInputStream(); int responseCode = httpConnection.getResponseCode(); if (responseCode != 200) { if (responseCode == 429 && httpConnection.getHeaderField("Retry-After") != null) { double sleepFloatingPoint = Double.valueOf(httpConnection.getHeaderField("Retry-After")); double sleepMillis = 1000 * sleepFloatingPoint; Thread.sleep((long) sleepMillis); return getContent(endpoint); } throw new RuntimeException("Response code was not 200. Detected response was " + responseCode); } String output; Reader reader = null; try { reader = new BufferedReader(new InputStreamReader(response, "UTF-8")); StringBuilder builder = new StringBuilder(); char[] buffer = new char[8192]; int read; while ((read = reader.read(buffer, 0, buffer.length)) > 0) { builder.append(buffer, 0, read); } output = builder.toString(); } finally { if (reader != null) { try { reader.close(); } catch (IOException logOrIgnore) { logOrIgnore.printStackTrace(); } } } return output; }
From source file:com.iStudy.Study.Renren.Util.java
/** * ??http//from w w w . java 2s.com * * @param url * @param method GET POST * @param params * @return */ public static String openUrl(String url, String method, Bundle params) { if (method.equals("GET")) { url = url + "?" + encodeUrl(params); } String response = ""; try { Log.d(LOG_TAG, method + " URL: " + url); HttpURLConnection conn = (HttpURLConnection) new URL(url).openConnection(); conn.setRequestProperty("User-Agent", USER_AGENT_SDK); if (!method.equals("GET")) { conn.setRequestMethod("POST"); conn.setDoOutput(true); conn.getOutputStream().write(encodeUrl(params).getBytes("UTF-8")); } InputStream is = null; int responseCode = conn.getResponseCode(); if (responseCode == 200) { is = conn.getInputStream(); } else { is = conn.getErrorStream(); } response = read(is); } catch (Exception e) { throw new RuntimeException(e.getMessage(), e); } return response; }