List of usage examples for java.net HttpURLConnection HTTP_OK
int HTTP_OK
To view the source code for java.net HttpURLConnection HTTP_OK.
Click Source Link
From source file:com.ijiaban.uitls.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. *///from www . j a v a 2 s . 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 == HttpURLConnection.HTTP_OK) { InputStream is = con.getInputStream(); String detail = readResponse(is); JSONObject jb = new JSONObject(detail); String name = getFirstName(detail); String image = getImage(detail); mFragment.show("Welcome " + name + "!"); mFragment.displayimage(image); is.close(); return; } else if (sc == 401) { GoogleAuthUtil.invalidateToken(mFragment.getActivity(), 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:org.ednovo.goorusearchwidget.WebService.java
public InputStream getHttpStream(String urlString) throws IOException { InputStream in = null;//from w w w.j a v a2s. c o m int response = -1; URL url = new URL(urlString); URLConnection conn = url.openConnection(); if (!(conn instanceof HttpURLConnection)) throw new IOException("Not an HTTP connection"); try { HttpURLConnection httpConn = (HttpURLConnection) conn; httpConn.setAllowUserInteraction(false); httpConn.setInstanceFollowRedirects(true); httpConn.setRequestMethod("GET"); httpConn.connect(); response = httpConn.getResponseCode(); Log.i("Response code :", "" + response); if (response == HttpURLConnection.HTTP_OK) { in = httpConn.getInputStream(); } } catch (Exception e) { throw new IOException("Error connecting"); } // end try-catch return in; }
From source file:ee.ria.xroad.proxy.clientproxy.WsdlRequestProcessor.java
HttpURLConnection createConnection(SoapMessageImpl message) throws Exception { URL url = new URL("http://127.0.0.1:" + SystemProperties.getClientProxyHttpPort()); HttpURLConnection con = (HttpURLConnection) url.openConnection(); con.setDoInput(true);/*from w w w .j av a2 s .c o m*/ con.setDoOutput(true); // Use the same timeouts as client proxy to server proxy connections. con.setConnectTimeout(SystemProperties.getClientProxyTimeout()); con.setReadTimeout(SystemProperties.getClientProxyHttpClientTimeout()); con.setRequestMethod("POST"); con.setRequestProperty(HttpHeaders.CONTENT_TYPE, MimeUtils.contentTypeWithCharset(MimeTypes.TEXT_XML, StandardCharsets.UTF_8.name())); IOUtils.write(message.getBytes(), con.getOutputStream()); if (con.getResponseCode() != HttpURLConnection.HTTP_OK) { throw new RuntimeException( "Received HTTP error: " + con.getResponseCode() + " - " + con.getResponseMessage()); } return con; }
From source file:net.sf.okapi.filters.drupal.DrupalConnector.java
/** * Get all nodes// w w w .j av a2s .co m * @return */ public List<NodeInfo> getNodes() { URL url; HttpURLConnection conn; List<NodeInfo> nodes = new ArrayList<NodeInfo>(); try { url = new URL(host + "rest/node"); conn = createConnection(url, "GET", false); if (conn.getResponseCode() != HttpURLConnection.HTTP_OK) { conn.disconnect(); throw new RuntimeException("Operation failed: " + conn.getResponseCode()); } BufferedReader reader = new BufferedReader(new InputStreamReader(conn.getInputStream())); JSONParser parser = new JSONParser(); JSONArray array = (JSONArray) parser.parse(reader); for (Object object : array) { JSONObject node = (JSONObject) object; NodeInfo ni = new NodeInfo((String) node.get("vid"), true); ni.setTitle((String) node.get("title")); ni.setType((String) node.get("type")); nodes.add(ni); } conn.disconnect(); } catch (MalformedURLException e) { e.printStackTrace(); } catch (IOException e) { e.printStackTrace(); } catch (ParseException e) { e.printStackTrace(); } return nodes; }
From source file:com.github.dozermapper.core.builder.xml.SchemaLSResourceResolver.java
/** * Attempts to open a http connection for the systemId resource, and follows the first redirect * * @param systemId url to the XSD//from w w w. j av a 2 s .c o m * @return stream to XSD * @throws IOException if fails to find XSD */ private InputStream resolveFromURL(String systemId) throws IOException { LOG.debug("Trying to download [{}]", systemId); URL obj = new URL(systemId); HttpURLConnection conn = (HttpURLConnection) obj.openConnection(); int status = conn.getResponseCode(); if ((status != HttpURLConnection.HTTP_OK) && (status == HttpURLConnection.HTTP_MOVED_TEMP || status == HttpURLConnection.HTTP_MOVED_PERM || status == HttpURLConnection.HTTP_SEE_OTHER)) { LOG.debug("Received status of {}, attempting to follow Location header", status); String newUrl = conn.getHeaderField("Location"); conn = (HttpURLConnection) new URL(newUrl).openConnection(); } return conn.getInputStream(); }
From source file:net.sf.ehcache.constructs.web.filter.GzipFilterTest.java
/** * Tests that a page which is storeGzipped is not gzipped when the user agent does not accept gzip encoding *///from www .ja v a 2 s . c o m public void testNotGzippedWhenNotAcceptEncodingHomePage() throws Exception { WebConversation client = createWebConversation(false); String url = buildUrl("/GzipOnlyPage.jsp"); WebResponse response = client.getResponse(url); assertNotNull(response); assertEquals(HttpURLConnection.HTTP_OK, response.getResponseCode()); String responseURL = response.getURL().toString(); assertEquals(url, responseURL); assertFalse("gzip".equals(response.getHeaderField("Content-Encoding"))); }
From source file:de.ub0r.android.websms.connector.discotel.ConnectorDiscotel.java
/** * Login to service.discoplus.de./*w ww. ja v a 2s . c o m*/ * * @param context * {@link Context} * @param command * {@link ConnectorCommand} * @throws IOException * IOException */ private void dpDoLogin(final Context context, // . final ConnectorCommand command) throws IOException { Log.d(TAG, "dpDoLogin()"); final SharedPreferences p = PreferenceManager.getDefaultSharedPreferences(context); ArrayList<BasicNameValuePair> postData = // . new ArrayList<BasicNameValuePair>(NUM_VARS_LOGIN); postData.add(new BasicNameValuePair("destination", LOGIN_DP_DEST)); String genlogin = Utils.getSender(context, command.getDefSender()); Log.d(TAG, "genlogin: " + genlogin); genlogin = Utils.international2national(command.getDefPrefix(), genlogin); Log.d(TAG, "genlogin: " + genlogin); postData.add(new BasicNameValuePair("credential_0", genlogin)); Log.d(TAG, "genlogin: " + genlogin); postData.add(new BasicNameValuePair("credential_1", p.getString(Preferences.PREFS_PASSWORD, ""))); HttpOptions o = new HttpOptions(ENCODING); o.addFormParameter(postData); o.userAgent = TARGET_AGENT; o.trustAll = Preferences.getTrustAll(p); o.knownFingerprints = TRUSTED_CERTS; o.url = URL_DP_LOGIN; HttpResponse response = Utils.getHttpClient(o); postData = null; int resp = response.getStatusLine().getStatusCode(); if (resp != HttpURLConnection.HTTP_OK) { throw new WebSMSException(context, R.string.error_http, "" + resp); } String htmlText = Utils.stream2str(response.getEntity().getContent()); Log.d(TAG, "----HTTP RESPONSE---"); Log.d(TAG, htmlText); Log.d(TAG, "----HTTP RESPONSE---"); if (!htmlText.contains(CHECK_DP_LOGIN)) { Log.e(TAG, "HTTP Status Line: " + response.getStatusLine().toString()); Log.e(TAG, "HTTP Headers:"); for (Header h : response.getAllHeaders()) { Log.e(TAG, h.getName() + ": " + h.getValue()); } Log.e(TAG, "HTTP Body:"); for (String l : htmlText.split("\n")) { Log.e(TAG, l); } Utils.clearCookies(); throw new WebSMSException(context, R.string.error_pw); } // update balance String balance = ""; int i = htmlText.indexOf(CHECK_DP_BALANCE1); if (i > 0) { htmlText = htmlText.substring(i, htmlText.indexOf(" EUR", i)); Log.d(TAG, htmlText); htmlText = htmlText.substring(htmlText.lastIndexOf(">") + 1); balance = htmlText + "\u20ac"; Log.d(TAG, "balance: " + balance); } // update free balance o = new HttpOptions(ENCODING); o.userAgent = TARGET_AGENT; o.trustAll = Preferences.getTrustAll(p); o.knownFingerprints = TRUSTED_CERTS; o.url = URL_DP_SEND; response = Utils.getHttpClient(o); resp = response.getStatusLine().getStatusCode(); if (resp != HttpURLConnection.HTTP_OK) { Log.e(TAG, "HTTP Status Line: " + response.getStatusLine().toString()); Log.e(TAG, "HTTP Headers:"); for (Header h : response.getAllHeaders()) { Log.e(TAG, h.getName() + ": " + h.getValue()); } Log.e(TAG, "HTTP Body:"); for (String l : htmlText.split("\n")) { Log.e(TAG, l); } Utils.clearCookies(); throw new WebSMSException(context, R.string.error_http, "" + resp); } htmlText = Utils.stream2str(response.getEntity().getContent()); Log.d(TAG, "----HTTP RESPONSE---"); Log.d(TAG, htmlText); Log.d(TAG, "----HTTP RESPONSE---"); i = htmlText.indexOf(CHECK_DP_BALANCE2); if (i < 0) { Log.e(TAG, "HTTP Status Line: " + response.getStatusLine().toString()); Log.e(TAG, "HTTP Headers:"); for (Header h : response.getAllHeaders()) { Log.e(TAG, h.getName() + ": " + h.getValue()); } Log.e(TAG, "HTTP Body:"); for (String l : htmlText.split("\n")) { Log.e(TAG, l); } Utils.clearCookies(); throw new WebSMSException(context, R.string.error); } htmlText = htmlText.substring(1, i); Log.d(TAG, "----HTTP RESPONSE---"); Log.d(TAG, htmlText); Log.d(TAG, "----HTTP RESPONSE---"); i = htmlText.lastIndexOf(">"); Log.d(TAG, "i: " + i); ++i; Log.d(TAG, "i: " + i); final int j = htmlText.lastIndexOf(" "); Log.d(TAG, "j: " + j); if (!TextUtils.isEmpty(balance)) { balance += "/"; } if (j < i) { balance += htmlText.substring(i); } else { balance += htmlText.substring(i, j); } Log.d(TAG, "balance: " + balance); this.getSpec(context).setBalance(balance); }
From source file:fr.Axeldu18.PterodactylAPI.Methods.POSTMethods.java
public String call(String methodURL, String data) { try {//from w w w.j a v a 2 s.co m URL url = new URL(methodURL); HttpURLConnection connection = (HttpURLConnection) url.openConnection(); String hmac = main.getPublicKey() + "." + main.hmac(methodURL + data); System.out.println("DEBUG CALL: " + methodURL); System.out.println("DEBUG CALL2: " + methodURL + data); System.out.println("DEBUG CALL3: " + hmac); connection.setRequestMethod("POST"); connection.setRequestProperty("User-Agent", "Pterodactyl Java-API"); connection.setRequestProperty("Authorization", "Bearer " + hmac.replaceAll("\n", "")); connection.setRequestProperty("Content-Type", "application/json"); connection.setDoOutput(true); DataOutputStream wr = new DataOutputStream(connection.getOutputStream()); wr.writeBytes(data); wr.flush(); wr.close(); int responseCode = connection.getResponseCode(); if (responseCode == HttpURLConnection.HTTP_OK) { return main.readResponse(connection.getInputStream()).toString(); } else { return main.readResponse(connection.getErrorStream()).toString(); } } catch (Exception e) { main.log(Level.SEVERE, e.getMessage()); e.printStackTrace(); return null; } }
From source file:com.jacr.instagramtrendreader.Main.java
private boolean isOnline(int timeout) { // Test 1: Is GPRS / Wifi port ON? ConnectivityManager cm = (ConnectivityManager) getSystemService(Context.CONNECTIVITY_SERVICE); NetworkInfo netInfo = cm.getActiveNetworkInfo(); if (netInfo != null && netInfo.isConnected()) { try {/*from w ww . j a v a 2s.co m*/ // Test 2: Ping specific url URL url = new URL("http://www.google.com"); HttpURLConnection urlc = (HttpURLConnection) url.openConnection(); urlc.setConnectTimeout(timeout); urlc.connect(); if (urlc.getResponseCode() == HttpURLConnection.HTTP_OK) { return true; } } catch (MalformedURLException e1) { e1.printStackTrace(); } catch (IOException e) { e.printStackTrace(); } } return false; }
From source file:com.cgxlib.xq.rebind.JsniBundleGenerator.java
/** * Get the content of a javascript source. It supports remote sources hosted in CDN's. *//*from w w w. ja v a 2 s. c o m*/ private String getContent(TreeLogger logger, String path, String src) throws UnableToCompleteException { HttpURLConnection connection = null; InputStream in = null; try { if (!src.matches("(?i)https?://.*")) { String file = path + "/" + src; logger.log(TreeLogger.INFO, getClass().getSimpleName() + " - importing external javascript: " + file); in = this.getClass().getClassLoader().getResourceAsStream(file); if (in == null) { logger.log(TreeLogger.ERROR, "Unable to read javascript file: " + file); } } else { logger.log(TreeLogger.INFO, getClass().getSimpleName() + " - downloading external javascript: " + src); URL url = new URL(src); connection = (HttpURLConnection) url.openConnection(); connection.setRequestProperty("Accept-Encoding", "gzip, deflate"); connection.setRequestProperty("Host", url.getHost()); connection.setConnectTimeout(3000); connection.setReadTimeout(3000); int status = connection.getResponseCode(); if (status != HttpURLConnection.HTTP_OK) { logger.log(TreeLogger.ERROR, "Server Error: " + status + " " + connection.getResponseMessage()); throw new UnableToCompleteException(); } String encoding = connection.getContentEncoding(); in = connection.getInputStream(); if ("gzip".equalsIgnoreCase(encoding)) { in = new GZIPInputStream(in); } else if ("deflate".equalsIgnoreCase(encoding)) { in = new InflaterInputStream(in); } } return inputStreamToString(in); } catch (IOException e) { logger.log(TreeLogger.ERROR, "Error: " + e.getMessage()); throw new UnableToCompleteException(); } finally { if (connection != null) { connection.disconnect(); } } }