List of usage examples for java.net HttpURLConnection connect
public abstract void connect() throws IOException;
From source file:com.android.projectz.teamrocket.thebusapp.activities.SplashScreenActivity.java
/** * permette di capire se il server esterno attualmente disponibile oppure offline * * @return boolean che identifica se il server online o offline */// w w w . j av a 2 s . c o m private boolean checkConnectionToServer() { if (android.os.Build.VERSION.SDK_INT > 9) { //questo per i permessi OBBLIGATORIO StrictMode.ThreadPolicy policy = new StrictMode.ThreadPolicy.Builder().permitAll().build(); StrictMode.setThreadPolicy(policy); } URL url = null; HttpURLConnection urlConnection = null; try { url = new URL(SharedPreferencesUtils.getWebsiteUrl(this) + "/app/altra_prova.php"); urlConnection = (HttpURLConnection) url.openConnection(); urlConnection.connect(); if (urlConnection.getResponseCode() == HttpURLConnection.HTTP_OK) { urlConnection.disconnect(); return true; } return false; } catch (IOException e) { e.printStackTrace(); if (!SharedPreferencesUtils.getWebsiteUrl(this).equals("http://thebusapp.orgfree.com")) { urlConnection.disconnect(); SharedPreferencesUtils.setWebsiteUrl(this, "http://thebusapp.orgfree.com"); checkConnectionToServer(); } return false; } }
From source file:org.sufficientlysecure.keychain.keyimport.HkpKeyServer.java
private String query(String request) throws QueryException, HttpError { InetAddress ips[];//from w w w .j a v a 2 s . c o m try { ips = InetAddress.getAllByName(mHost); } catch (UnknownHostException e) { throw new QueryException(e.toString()); } for (int i = 0; i < ips.length; ++i) { try { String url = "http://" + ips[i].getHostAddress() + ":" + mPort + request; Log.d(Constants.TAG, "hkp keyserver query: " + url); URL realUrl = new URL(url); HttpURLConnection conn = (HttpURLConnection) realUrl.openConnection(); conn.setConnectTimeout(5000); conn.setReadTimeout(25000); conn.connect(); int response = conn.getResponseCode(); if (response >= 200 && response < 300) { return readAll(conn.getInputStream(), conn.getContentEncoding()); } else { String data = readAll(conn.getErrorStream(), conn.getContentEncoding()); throw new HttpError(response, data); } } catch (MalformedURLException e) { // nothing to do, try next IP } catch (IOException e) { // nothing to do, try next IP } } throw new QueryException("querying server(s) for '" + mHost + "' failed"); }
From source file:at.florian_lentsch.expirysync.net.JsonCaller.java
/** * Calls a server path and returns a json object with the server's response * @param path the url to call// w w w . j a v a 2 s . c o m * @param method either {@code "GET"} or {@code "POST"} * @param params parameters to send to the server * @return the server's response * @throws MalformedURLException if the url is invalid * @throws IOException something went wrong while talking to the server * @throws ProtocolException if an invalid {@code method} has been passed * @throws JSONException invalid response received from the server */ public JSONObject performJsonCall(String path, String method, JSONObject params) throws MalformedURLException, IOException, ProtocolException, JSONException { String getParams = ""; if (params != null && method == METHOD_GET) { getParams = jsonToGetParams(params); } URL url = new URL(this.host.toString() + path + getParams); boolean outputAvailable = (params != null && method != METHOD_GET); //connect to the server: HttpURLConnection connection = (HttpURLConnection) url.openConnection(); prepareConnection(connection, method, outputAvailable); connection.addRequestProperty("Accept-Language", Locale.getDefault().getLanguage()); connection.connect(); // write out: if (outputAvailable) { // in case there are params and this is a POST request: writeParams(connection, params); } // read: determineTimeSkew(connection); storeCookies(connection); JSONObject obj = readJSON(connection); return obj; }
From source file:com.google.android.apps.santatracker.service.RemoteApiProcessor.java
/** * Downloads the given URL and return/* w w w .j ava 2 s . c o m*/ */ protected String downloadUrl(String myurl) throws IOException { InputStream is = null; // Only display the first 500 characters of the retrieved // web page content. // int len = 500; try { URL url = new URL(myurl); HttpURLConnection conn = (HttpURLConnection) url.openConnection(); conn.setReadTimeout(10000); conn.setConnectTimeout(15000); conn.setRequestMethod("GET"); conn.setDoInput(true); // Starts the query conn.connect(); int response = conn.getResponseCode(); if (!isValidHeader(conn)) { // not a valid header Log.d(TAG, "Santa communication failure."); return null; } else if (response != 200) { Log.d(TAG, "Santa communication failure " + response); return null; } else { is = conn.getInputStream(); // Convert the InputStream into a string return read(is).toString(); } // Makes sure that the InputStream is closed } finally { if (is != null) { is.close(); } } }
From source file:com.intravel.Facebook.Util.java
/** * Connect to an HTTP URL and return the response as a string. * * Note that the HTTP method override is used on non-GET requests. (i.e. * requests are made as "POST" with method specified in the body). * * @param url - the resource to open: must be a welformed URL * @param method - the HTTP method to use ("GET", "POST", etc.) * @param params - the query parameter for the URL (e.g. access_token=foo) * @return the URL contents as a String// www. j a v a2 s . c o m * @throws MalformedURLException - if the URL format is invalid * @throws IOException - if a network problem occurs */ public static String openUrl(String url, String method, Bundle params) throws MalformedURLException, IOException { // random string as boundary for multi-part http post String strBoundary = "3i2ndDfv2rTHiSisAbouNdArYfORhtTPEefj3q2f"; String endLine = "\r\n"; OutputStream os; if (method.equals("GET")) { url = url + "?" + encodeUrl(params); } // else{ // url = url + "&" + encodeUrl(params); // } Log.d("Facebook-Util", method + " URL: " + url); HttpURLConnection conn = (HttpURLConnection) new URL(url).openConnection(); conn.setRequestProperty("User-Agent", System.getProperties().getProperty("http.agent") + " FacebookAndroidSDK"); if (!method.equals("GET")) { Bundle dataparams = new Bundle(); for (String key : params.keySet()) { if (params.getByteArray(key) != null) { dataparams.putByteArray(key, params.getByteArray(key)); } } // use method override if (!params.containsKey("method")) { params.putString("method", method); } if (params.containsKey("access_token")) { String decoded_token = URLDecoder.decode(params.getString("access_token")); params.putString("access_token", decoded_token); } conn.setRequestMethod("POST"); conn.setRequestProperty("Content-Type", "multipart/form-data;boundary=" + strBoundary); conn.setDoOutput(true); conn.setDoInput(true); conn.setRequestProperty("Connection", "Keep-Alive"); conn.connect(); os = new BufferedOutputStream(conn.getOutputStream()); os.write(("--" + strBoundary + endLine).getBytes()); os.write((encodePostBody(params, strBoundary)).getBytes()); os.write((endLine + "--" + strBoundary + endLine).getBytes()); if (!dataparams.isEmpty()) { for (String key : dataparams.keySet()) { os.write(("Content-Disposition: form-data; filename=\"" + key + "\"" + endLine).getBytes()); os.write(("Content-Type: content/unknown" + endLine + endLine).getBytes()); os.write(dataparams.getByteArray(key)); os.write((endLine + "--" + strBoundary + endLine).getBytes()); } } os.flush(); } String response = ""; try { response = read(conn.getInputStream()); } catch (FileNotFoundException e) { // Error Stream contains JSON that we can parse to a FB error response = read(conn.getErrorStream()); } return response; }
From source file:org.thialfihar.android.apg.keyimport.HkpKeyserver.java
private String query(String request) throws QueryFailedException, HttpError { InetAddress ips[];/* w w w. j ava 2s . co m*/ try { ips = InetAddress.getAllByName(mHost); } catch (UnknownHostException e) { throw new QueryFailedException(e.toString()); } for (int i = 0; i < ips.length; ++i) { try { String url = "http://" + ips[i].getHostAddress() + ":" + mPort + request; Log.d(Constants.TAG, "hkp keyserver query: " + url); URL realUrl = new URL(url); HttpURLConnection conn = (HttpURLConnection) realUrl.openConnection(); conn.setConnectTimeout(5000); conn.setReadTimeout(25000); conn.connect(); int response = conn.getResponseCode(); if (response >= 200 && response < 300) { return readAll(conn.getInputStream(), conn.getContentEncoding()); } else { String data = readAll(conn.getErrorStream(), conn.getContentEncoding()); throw new HttpError(response, data); } } catch (MalformedURLException e) { // nothing to do, try next IP } catch (IOException e) { // nothing to do, try next IP } } throw new QueryFailedException("querying server(s) for '" + mHost + "' failed"); }
From source file:ch.pec0ra.mobilityratecalculator.DistanceCalculator.java
private String downloadUrl(String myurl) throws IOException { InputStream is = null;//from w w w .j a v a2 s . c o m try { URL url = new URL(myurl); HttpURLConnection conn = (HttpURLConnection) url.openConnection(); conn.setReadTimeout(10000 /* milliseconds */); conn.setConnectTimeout(15000 /* milliseconds */); conn.setRequestMethod("GET"); conn.setDoInput(true); // Starts the query conn.connect(); conn.getResponseCode(); is = conn.getInputStream(); String responseAsString = CharStreams.toString(new InputStreamReader(is)); return responseAsString; // Makes sure that the InputStream is closed after the app is // finished using it. } finally { if (is != null) { is.close(); } } }
From source file:utils.httpUtil_inThread.java
/** * ?(?)//www . j ava2 s .co m * * @return ?null? */ public byte[] HttpGetBitmap(String url, String cookie, int timeout_connection, int timeout_read) { byte[] bytes = null; InputStream is = null; try { //?? if (timeout_connection <= 1000) timeout_connection = timeout_pic_connection; if (timeout_read < 1000) timeout_read = timeout_pic_read; URL bitmapURL = new URL(url); HttpURLConnection conn = (HttpURLConnection) bitmapURL.openConnection(); if (cookie != null && !cookie.equals("")) conn.setRequestProperty("Cookie", cookie); //cookie conn.setConnectTimeout(timeout_connection); conn.setReadTimeout(timeout_read); conn.setDoInput(true); conn.connect(); //? is = conn.getInputStream(); bytes = InputStreamUtils.InputStreamTOByte(is); } catch (Exception e) { abstract_LogUtil.e(this, "[]" + e.toString()); } finally { try { if (is != null) is.close(); } catch (Exception e) { abstract_LogUtil.e(this, "[InputStream]"); } } return bytes; }
From source file:alluxio.worker.block.BlockWorkerClientRestApiTest.java
@Test public void writeBlock() throws Exception { Map<String, String> params = new HashMap<>(); params.put("blockId", Long.toString(BLOCK_ID)); params.put("sessionId", Long.toString(SESSION_ID)); params.put("offset", "0"); params.put("length", Long.toString(INITIAL_BYTES)); TestCase testCase = new TestCase(mHostname, mPort, getEndpoint(BlockWorkerClientRestServiceHandler.WRITE_BLOCK), params, HttpMethod.POST, null); HttpURLConnection connection = (HttpURLConnection) testCase.createURL().openConnection(); connection.setRequestProperty("Content-Type", MediaType.APPLICATION_OCTET_STREAM); connection.setRequestMethod(testCase.getMethod()); connection.setDoOutput(true);//from w ww. ja va 2 s. c o m connection.connect(); connection.getOutputStream().write(BYTE_BUFFER.array()); Assert.assertEquals(testCase.getEndpoint(), Response.Status.OK.getStatusCode(), connection.getResponseCode()); Assert.assertEquals("", testCase.getResponse(connection)); // Verify that the right data was written. mBlockWorker.commitBlock(SESSION_ID, BLOCK_ID); long lockId = mBlockWorker.lockBlock(SESSION_ID, BLOCK_ID); String file = mBlockWorker.readBlock(SESSION_ID, BLOCK_ID, lockId); byte[] result = new byte[INITIAL_BYTES]; IOUtils.readFully(new FileInputStream(file), result); Assert.assertArrayEquals(BYTE_BUFFER.array(), result); }
From source file:com.orange.oidc.tim.service.HttpOpenidConnect.java
static String getTimUserInfo(String server_url, String tim_access_token) { // android.os.Debug.waitForDebugger(); // default result String result = null;// w w w . j a va 2 s . c o m // check if server is valid if (isEmpty(server_url) || isEmpty(tim_access_token)) { Logd(TAG, "getTimUserInfo no server url or tim_access_token"); return null; } if (!server_url.endsWith("/")) server_url += "/"; // get user info endpoint String userinfo_endpoint = getEndpointFromConfigOidc("userinfo_endpoint", server_url); if (isEmpty(userinfo_endpoint)) { Logd(TAG, "getTimUserInfo : could not get endpoint on server : " + server_url); return null; } // build connection HttpURLConnection huc = getHUC(userinfo_endpoint); huc.setInstanceFollowRedirects(false); huc.setRequestProperty("Content-Type", "application/x-www-form-urlencoded"); huc.setRequestProperty("Authorization", "Bearer " + tim_access_token); Logd("getTimUserInfo", "bearer: " + tim_access_token); try { // try to establish connection huc.connect(); // get result int responseCode = huc.getResponseCode(); Logd(TAG, "getTimUserInfo 2 response: " + responseCode); // if 200, read http body if (responseCode == 200) { InputStream is = huc.getInputStream(); result = convertStreamToString(is); is.close(); Logd(TAG, "getTimUserInfo 2 result: " + result); } else { // result = "response code: "+responseCode; } // close connection huc.disconnect(); } catch (Exception e) { Log.e(TAG, "getTimUserInfo FAILED"); e.printStackTrace(); } return result; }