List of usage examples for java.net HttpURLConnection getURL
public URL getURL()
From source file:com.googlesource.gerrit.plugins.its.jira.restapi.JiraRestApi.java
/** * Checks if the connection returned one of the provides pass or fail Codes. If not, an * IOException exception is thrown. If it was part of the list, then the actual response code is * returned. returns true if valid response is returned, otherwise false *///from w w w . j a v a 2 s. com private boolean validateResponse(HttpURLConnection conn, int passCode, int[] failCodes) throws IOException { responseCode = conn.getResponseCode(); if (responseCode == passCode) { return true; } if ((failCodes == null) || (!ArrayUtils.contains(failCodes, responseCode))) { throw new IOException("Request failed: " + conn.getURL() + " - " + conn.getResponseCode() + " - " + conn.getResponseMessage()); } return false; }
From source file:com.cloudant.http.internal.interceptors.CookieInterceptor.java
private boolean storeCookiesFromResponse(HttpURLConnection connection) { // Store any cookies from the response in the CookieManager try {/*from w ww . ja v a 2s .c o m*/ logger.finest("Storing cookie."); cookieManager.put(connection.getURL().toURI(), connection.getHeaderFields()); return true; } catch (IOException e) { logger.log(Level.SEVERE, "Failed to read cookie response header", e); return false; } catch (URISyntaxException e) { logger.log(Level.SEVERE, "Failed to convert request URL to URI for cookie storage."); return false; } }
From source file:uk.org.rivernile.edinburghbustracker.android.twitter.TwitterUpdatesLoader.java
/** * {@inheritDoc}/*from w w w . j ava 2 s .c o m*/ */ @Override public TwitterLoaderResult loadInBackground() { final ArrayList<TwitterNewsItem> items = new ArrayList<TwitterNewsItem>(); final StringBuilder urlBuilder = new StringBuilder(REQUEST_URL); urlBuilder.append(ApiKey.getHashedKey()); urlBuilder.append("&random=").append(random.nextInt()); byte error; try { // Create URL object. final URL u = new URL(urlBuilder.toString()); // Open the connection to the HTTP server. final HttpURLConnection con = (HttpURLConnection) u.openConnection(); // Buffer the input. final BufferedReader in = new BufferedReader(new InputStreamReader(con.getInputStream())); // Check to see if the URL we've connected to is what we expected. if (u.getHost().equals(con.getURL().getHost())) { // All text will be put in to a StringBuilder. final StringBuilder sb = new StringBuilder(); String lineIn; // Keep accepting input until there is no more. while ((lineIn = in.readLine()) != null) { sb.append(lineIn); } // Parse the JSON. error = parseJSON(items, sb.toString()); } else { error = ERROR_URLMISMATCH; } // Remember to release resources. in.close(); con.disconnect(); } catch (MalformedURLException e) { error = ERROR_URLERR; } catch (IOException e) { error = ERROR_IOERR; } catch (JSONException e) { error = ERROR_PARSEERR; } // Error codes are >= 0, so if the error code matches this, create an // error object, otherwise create a result object. if (error < 0) { return new TwitterLoaderResult(items); } else { return new TwitterLoaderResult(error); } }
From source file:org.jumpmind.symmetric.transport.http.HttpIncomingTransport.java
/** * This method support redirection from an http connection to an https connection. * See {@link http://java.sun.com/j2se/1.4.2/docs/guide/deployment/deployment-guide/upgrade-guide/article-17.html} * for more information./*from w w w . ja va 2 s . co m*/ * * @param connection * @return * @throws IOException */ private HttpURLConnection openConnectionCheckRedirects(HttpURLConnection connection) throws IOException { boolean redir; int redirects = 0; do { connection.setInstanceFollowRedirects(false); redir = false; int stat = connection.getResponseCode(); if (stat >= 300 && stat <= 307 && stat != 306 && stat != HttpURLConnection.HTTP_NOT_MODIFIED) { URL base = connection.getURL(); redirectionUrl = connection.getHeaderField("Location"); URL target = null; if (redirectionUrl != null) { target = new URL(base, redirectionUrl); } connection.disconnect(); // Redirection should be allowed only for HTTP and HTTPS // and should be limited to 5 redirections at most. if (target == null || !(target.getProtocol().equals("http") || target.getProtocol().equals("https")) || redirects >= 5) { throw new SecurityException("illegal URL redirect"); } redir = true; connection = HttpTransportManager.openConnection(target, getBasicAuthUsername(), getBasicAuthPassword()); connection.setConnectTimeout(httpTimeout); connection.setReadTimeout(httpTimeout); redirects++; } } while (redir); return connection; }
From source file:org.holistic.ws_proxy.WSProxyHelper.java
private void doGet(HttpServletRequest req, HttpServletResponse resp) throws Exception { HttpURLConnection m_objURLConnection = null; m_objURLConnection = openurl(get_request(req)); // resp.setStatus(m_objURLConnection.getResponseCode()); set_headers2urlconn(req, m_objURLConnection); m_objURLConnection.setRequestProperty("host", m_objURLConnection.getURL().getHost() + ":" + m_objURLConnection.getURL().getPort()); resp.setStatus(m_objURLConnection.getResponseCode()); if (m_objURLConnection.getContentType() != null) resp.setContentType(m_objURLConnection.getContentType()); get_endpointstream(resp, m_objURLConnection); }
From source file:com.mobile.godot.core.service.task.GodotAction.java
@Override public void run() { System.out.println("inside runnable"); android.os.Process.setThreadPriority(android.os.Process.THREAD_PRIORITY_BACKGROUND); URL url = GodotURLUtils.parseToURL(this.mServlet, this.mParams); System.out.println("url: " + url); HttpURLConnection connection = null; InputStream iStream;//from w w w . ja va 2s . c o m InputStream eStream; int responseCode = 0; String data = null; try { connection = (HttpURLConnection) url.openConnection(); connection.setRequestMethod("GET"); connection.setDoInput(true); connection.setDoOutput(true); connection.connect(); if (!url.getHost().equals(connection.getURL().getHost())) { this.mHandler.obtainMessage(GodotMessage.Error.REDIRECTION_ERROR).sendToTarget(); connection.disconnect(); return; } try { iStream = new BufferedInputStream(connection.getInputStream()); BufferedReader bReader = new BufferedReader(new InputStreamReader(iStream)); data = bReader.readLine(); responseCode = connection.getResponseCode(); } catch (IOException exc) { eStream = new BufferedInputStream(connection.getErrorStream()); BufferedReader bReader = new BufferedReader(new InputStreamReader(eStream)); data = bReader.readLine(); responseCode = connection.getResponseCode(); } finally { if (data != null) { this.mHandler.obtainMessage(this.mMessageMap.get(responseCode), data).sendToTarget(); } else { this.mHandler.obtainMessage(this.mMessageMap.get(responseCode)).sendToTarget(); } } } catch (IOException exc) { this.mHandler.obtainMessage(GodotMessage.Error.SERVER_ERROR).sendToTarget(); } finally { connection.disconnect(); } }
From source file:de.ub0r.android.callmeter.ui.prefs.PreferencesPlain.java
private void loadRules() { new AsyncTask<Void, Void, JSONObject>() { @Override// w w w.j a v a 2 s . com protected JSONObject doInBackground(final Void... params) { try { String l; StringBuilder sb = new StringBuilder(); File f = new File(PreferencesPlain.this.getCacheDir(), "ub0rrules.json"); if (f.exists() && f.lastModified() + CACHE_TIMEOUT > System.currentTimeMillis()) { Log.i(TAG, "found cached data: " + f.getAbsolutePath()); BufferedReader r = new BufferedReader(new FileReader(f)); while ((l = r.readLine()) != null) { sb.append(l); } r.close(); } if (sb.length() == 0) { if (f.exists()) { f.delete(); } HttpURLConnection c = (HttpURLConnection) new URL( "http://ub0r.de/android/callmeter/rulesets/rulesets.json").openConnection(); Log.i(TAG, "load new data: " + c.getURL()); BufferedReader r = new BufferedReader(new InputStreamReader(c.getInputStream())); FileWriter w = new FileWriter(f); while ((l = r.readLine()) != null) { sb.append(l); w.write(l); } r.close(); w.close(); } try { return new JSONObject(sb.toString()); } catch (JSONException e) { Log.e(TAG, "JSON Error", e); Log.e(TAG, "JSON: " + sb.toString()); return null; } } catch (IOException e) { Log.e(TAG, "IOError", e); } return null; } @SuppressWarnings({ "deprecation", "rawtypes" }) @Override protected void onPostExecute(final JSONObject result) { if (result == null) { Toast.makeText(PreferencesPlain.this, R.string.err_export_read, Toast.LENGTH_LONG).show(); return; } PreferenceGroup base = (PreferenceGroup) PreferencesPlain.this.findPreference("import_rules_users"); PreferenceManager pm = base.getPreferenceManager(); // delete old base.removeAll(); base = (PreferenceGroup) PreferencesPlain.this.findPreference("import_rules_base"); // build list ArrayList<String> keys = new ArrayList<String>(result.length()); Iterator it = result.keys(); while (it.hasNext()) { keys.add(it.next().toString()); } Collections.sort(keys); keys.remove("common"); keys.add(0, "common"); OnPreferenceClickListener opcl = new OnPreferenceClickListener() { @Override public boolean onPreferenceClick(final Preference preference) { Intent intent = new Intent(PreferencesPlain.this, PreferencesRules.class); intent.putExtra(PreferencesRules.EXTRA_JSON, result.toString()); intent.putExtra(PreferencesRules.EXTRA_COUNTRY, preference.getKey()); PreferencesPlain.this.startActivity(intent); return true; } }; for (String k : keys) { PreferenceScreen p = pm.createPreferenceScreen(PreferencesPlain.this); p.setPersistent(false); p.setKey(k); p.setTitle(k); p.setOnPreferenceClickListener(opcl); base.addPreference(p); } } ; }.execute((Void) null); }
From source file:uk.org.rivernile.edinburghbustracker.android.livetimes.parser.EdinburghParser.java
/** * {@inheritDoc}// ww w . j av a2s .co m */ @Override public HashMap<String, BusStop> getBusStopData(final String[] stopCodes, final int numDepartures) throws BusParserException { if (stopCodes == null || stopCodes.length == 0) return null; // Build the URL. final StringBuilder sb = new StringBuilder(); sb.append(URL); sb.append(ApiKey.getHashedKey()); sb.append("&function=getBusTimes&"); final int len = stopCodes.length; if (len == 1) { sb.append("stopId="); sb.append(stopCodes[0]); sb.append('&'); } else { for (int i = 0; i < len; i++) { if (i >= 6) break; sb.append("stopId"); sb.append(i + 1); sb.append('='); sb.append(stopCodes[i]); sb.append('&'); } } sb.append("nb="); sb.append(numDepartures); // Add a random arg so the response isn't cached by the network proxies. sb.append("&random="); sb.append(rand.nextInt()); // TODO: review this code. I'm sure it could be done better. try { final URL url = new URL(sb.toString()); // Reset the StringBuilder because we're going to reuse it. sb.setLength(0); final HttpURLConnection conn = (HttpURLConnection) url.openConnection(); try { final BufferedInputStream is = new BufferedInputStream(conn.getInputStream()); // Check to see if the URL we connected to was what we expected. if (!url.getHost().equals(conn.getURL().getHost())) { is.close(); conn.disconnect(); throw new BusParserException(ERROR_URLMISMATCH); } int data; while ((data = is.read()) != -1) { sb.append((char) data); } } finally { conn.disconnect(); } return parseJSON(sb.toString()); } catch (MalformedURLException e) { throw new BusParserException(ERROR_CANNOTRESOLVE); } catch (IOException e) { throw new BusParserException(ERROR_NOCONNECTION); } catch (JSONException e) { throw new BusParserException(ERROR_PARSEERR); } }
From source file:edu.mit.mobile.android.net.DownloadLoader.java
@Override public Uri loadInBackground() { boolean alreadyHasDownload = false; if (!outdir.exists() && !outdir.mkdirs()) { mException = new IOException("could not mkdirs: " + outdir.getAbsolutePath()); return null; }// w w w. j ava 2 s. c om final String fname = mUrl.substring(mUrl.lastIndexOf('/')); final File outfile = new File(outdir, fname); alreadyHasDownload = outfile.exists() && outfile.length() > MINIMUM_REASONABLE_VIDEO_SIZE; final long lastModified = outfile.exists() ? outfile.lastModified() : 0; try { final NetworkInfo netInfo = mCm.getActiveNetworkInfo(); if (netInfo == null || !netInfo.isConnected()) { // no connection, but there's already a file. Hopefully it works! if (alreadyHasDownload) { return Uri.fromFile(outfile); } else { mException = new IOException(getContext().getString(R.string.err_no_data_connection)); return null; } } HttpURLConnection hc = (HttpURLConnection) new URL(mUrl).openConnection(); hc.setInstanceFollowRedirects(true); if (lastModified != 0) { hc.setIfModifiedSince(lastModified); } int resp = hc.getResponseCode(); if (resp >= 300 && resp < 400) { final String redirectUrl = hc.getURL().toExternalForm(); if (BuildConfig.DEBUG) { Log.d(TAG, "following redirect to " + redirectUrl); } hc = (HttpURLConnection) new URL(redirectUrl).openConnection(); if (lastModified != 0) { hc.setIfModifiedSince(lastModified); } resp = hc.getResponseCode(); } if (resp != HttpStatus.SC_OK && resp != HttpStatus.SC_NOT_MODIFIED) { Log.e(TAG, "got a non-200 response from server"); mException = new NetworkProtocolException("Received " + resp + " response from server"); return null; } if (resp == HttpStatus.SC_NOT_MODIFIED) { if (Constants.DEBUG) { Log.d(TAG, "got NOT MODIFIED"); } // verify the integrity of the file if (alreadyHasDownload) { if (Constants.DEBUG) { Log.d(TAG, fname + " has not been modified since it was downloaded last"); } return Uri.fromFile(outfile); } else { // re-request without the if-modified header. This shouldn't happen. hc = (HttpURLConnection) new URL(mUrl).openConnection(); final int responseCode = hc.getResponseCode(); if (responseCode != HttpStatus.SC_OK) { Log.e(TAG, "got a non-200 response from server"); mException = new NetworkProtocolException( "Received " + responseCode + " response from server"); return null; } } } final int contentLength = hc.getContentLength(); if (contentLength == 0) { Log.e(TAG, "got an empty response from server"); mException = new IOException("Received an empty response from server."); return null; } else if (contentLength < MINIMUM_REASONABLE_VIDEO_SIZE) { // this is probably not a // video Log.e(TAG, "got a very small response from server of length " + hc.getContentLength()); mException = new IOException("Received an unusually-small response from server."); return null; } boolean downloadSucceeded = false; try { final BufferedInputStream bis = new BufferedInputStream(hc.getInputStream()); final FileOutputStream fos = new FileOutputStream(outfile); if (Constants.DEBUG) { Log.d(TAG, "downloading..."); } StreamUtils.inputStreamToOutputStream(bis, fos); fos.close(); // store the server's last modified date in the filesystem outfile.setLastModified(hc.getLastModified()); downloadSucceeded = true; if (Constants.DEBUG) { Log.d(TAG, "done! Saved to " + outfile); } return Uri.fromFile(outfile); } finally { hc.disconnect(); // cleanup if this is the first attempt to download if (!alreadyHasDownload && !downloadSucceeded) { outfile.delete(); } } } catch (final IOException e) { Log.e(TAG, "error downloading file", e); mException = e; return null; } }
From source file:com.amastigote.xdu.query.module.EduSystem.java
private @Nullable JSONObject personalInfoQuery() throws IOException, JSONException { if (!checkIsLogin(ID)) { return null; }/* w w w.ja va 2s .c om*/ URL url = new URL(SYS_HOST + "xjInfoAction.do?oper=xjxx"); HttpURLConnection httpURLConnection = (HttpURLConnection) url.openConnection(); httpURLConnection.setRequestProperty("Cookie", "JSESSIONID=" + SYS_JSESSIONID); httpURLConnection.connect(); Document document = Jsoup.parse(httpURLConnection.getInputStream(), "gb2312", httpURLConnection.getURL().toString()); document = Jsoup.parse(document.toString().replaceAll(" ", "")); Elements elements1 = document.select("td[width=275]"); JSONObject jsonObject = new JSONObject(); jsonObject.put(StudentKey.ID, elements1.get(0).text()); jsonObject.put(StudentKey.NAME, elements1.get(1).text()); jsonObject.put(StudentKey.GENDER, elements1.get(6).text()); jsonObject.put(StudentKey.NATION, elements1.get(10).text()); jsonObject.put(StudentKey.NATIVE_PLACE, elements1.get(11).text()); jsonObject.put(StudentKey.DEPARTMENT, elements1.get(24).text()); jsonObject.put(StudentKey.MAJOR, elements1.get(25).text()); jsonObject.put(StudentKey.CLASS, elements1.get(28).text()); return jsonObject; }