List of usage examples for java.net HttpURLConnection connect
public abstract void connect() throws IOException;
From source file:in.leafco.wallet.ExchangeRatesProvider.java
private static float requestDogeBtcConversion(int provider) { HttpURLConnection connection = null; Reader reader = null;//from w w w . jav a2 s. c o m URL providerUrl; switch (provider) { case 0: providerUrl = LEAFPOOL_URL; break; case 1: providerUrl = VIRCUREX_URL; break; default: providerUrl = LEAFPOOL_URL; break; } try { connection = (HttpURLConnection) providerUrl.openConnection(); connection.setConnectTimeout(Constants.HTTP_TIMEOUT_MS); connection.setReadTimeout(Constants.HTTP_TIMEOUT_MS); connection.connect(); final int responseCode = connection.getResponseCode(); if (responseCode == HttpURLConnection.HTTP_OK) { reader = new InputStreamReader(new BufferedInputStream(connection.getInputStream(), 1024), Constants.UTF_8); final StringBuilder content = new StringBuilder(); Io.copy(reader, content); try { float rate; switch (provider) { case 0: /*rate = Float.parseFloat( json.getJSONObject("return") .getJSONObject("markets") .getJSONObject("LEAF") .getString("lasttradeprice"));*/ //For later use. rate = Float.parseFloat(content.toString()); break; case 1: final JSONObject json = new JSONObject(content.toString()); rate = Float.parseFloat(json.getString("value")); break; default: return -1; } return rate; } catch (NumberFormatException e) { log.debug("Couldn't get the current exchnage rate from provider " + String.valueOf(provider)); return -1; } } else { log.debug("http status " + responseCode + " when fetching " + providerUrl); } } catch (final Exception x) { log.debug("problem reading exchange rates", x); } finally { if (reader != null) { try { reader.close(); } catch (final IOException x) { // swallow } } if (connection != null) connection.disconnect(); } return -1; }
From source file:de.jdellay.wallet.ExchangeRatesProvider.java
private static float requestCcnBtcConversion(int provider) { HttpURLConnection connection = null; Reader reader = null;//from w w w . jav a2s . co m URL providerUrl; switch (provider) { case 0: providerUrl = CCNPOOL_URL; break; case 1: providerUrl = VIRCUREX_URL; break; default: providerUrl = CCNPOOL_URL; break; } try { connection = (HttpURLConnection) providerUrl.openConnection(); connection.setConnectTimeout(Constants.HTTP_TIMEOUT_MS); connection.setReadTimeout(Constants.HTTP_TIMEOUT_MS); connection.connect(); final int responseCode = connection.getResponseCode(); if (responseCode == HttpURLConnection.HTTP_OK) { reader = new InputStreamReader(new BufferedInputStream(connection.getInputStream(), 1024), Constants.UTF_8); final StringBuilder content = new StringBuilder(); Io.copy(reader, content); try { float rate; switch (provider) { case 0: /*rate = Float.parseFloat( json.getJSONObject("return") .getJSONObject("markets") .getJSONObject("CCN") .getString("lasttradeprice"));*/ //For later use. rate = Float.parseFloat(content.toString()); break; case 1: final JSONObject json = new JSONObject(content.toString()); rate = Float.parseFloat(json.getString("value")); break; default: return -1; } return rate; } catch (NumberFormatException e) { log.debug("Couldn't get the current exchnage rate from provider " + String.valueOf(provider)); return -1; } } else { log.debug("http status " + responseCode + " when fetching " + providerUrl); } } catch (final Exception x) { log.debug("problem reading exchange rates", x); } finally { if (reader != null) { try { reader.close(); } catch (final IOException x) { // swallow } } if (connection != null) connection.disconnect(); } return -1; }
From source file:com.roadwarrior.vtiger.client.NetworkUtilities.java
/** * Fetches the list of friend data updates from the server * /*from ww w. java2s. c o m*/ * @param account The account being synced. * @param authtoken The authtoken stored in AccountManager for this account * @param lastUpdated The last time that sync was performed * @return list The list of updates received from the server. */ public static List<User> fetchFriendUpdates(Account account, String auth_url, String authtoken, long serverSyncState/*Date lastUpdated*/, String type_contact) throws JSONException, ParseException, IOException, AuthenticationException { ArrayList<User> friendList = new ArrayList<User>(); ArrayList<NameValuePair> params = new ArrayList<NameValuePair>(); params.add(new BasicNameValuePair(PARAM_OPERATION, "sync")); params.add(new BasicNameValuePair(PARAM_SESSIONNAME, sessionName)); if (serverSyncState == 0) params.add(new BasicNameValuePair("modifiedTime", "878925701")); // il y a 14 ans.... else params.add(new BasicNameValuePair("modifiedTime", String.valueOf(serverSyncState))); params.add(new BasicNameValuePair("elementType", type_contact)); // "Accounts,Leads , Contacts... Log.d(TAG, "fetchFriendUpdates"); // params.add(new BasicNameValuePair(PARAM_QUERY, "select firstname,lastname,mobile,email,homephone,phone from Contacts;")); // if (lastUpdated != null) { // final SimpleDateFormat formatter = // new SimpleDateFormat("yyyy/MM/dd HH:mm"); // formatter.setTimeZone(TimeZone.getTimeZone("UTC")); // params.add(new BasicNameValuePair(PARAM_UPDATED, formatter // .format(lastUpdated))); // } // HTTP GET REQUEST URL url = new URL(auth_url + "/webservice.php?" + URLEncodedUtils.format(params, "utf-8")); HttpURLConnection con; con = (HttpURLConnection) url.openConnection(); con.setRequestMethod("GET"); con.setRequestProperty("Content-length", "0"); con.setRequestProperty("accept", "application/json"); con.setUseCaches(false); con.setAllowUserInteraction(false); int timeout = 10000; // si tiemout pas assez important la connection echouait =>IOEXception con.setConnectTimeout(timeout); con.setReadTimeout(timeout); con.connect(); int status = con.getResponseCode(); LastFetchOperationStatus = true; if (status == HttpURLConnection.HTTP_OK) { // Succesfully connected to the samplesyncadapter server and // authenticated. // Extract friends data in json format. BufferedReader br = new BufferedReader(new InputStreamReader(con.getInputStream())); StringBuilder sb = new StringBuilder(); String line; while ((line = br.readLine()) != null) { sb.append(line + "\n"); } br.close(); String response = sb.toString(); Log.i(TAG, "--response--"); // <Hack> to bypass vtiger 5.4 webservice bug: int idx = response.indexOf("{\"success"); response = response.substring(idx); Log.i(TAG, response); // </Hack> Log.i(TAG, "--response end--"); JSONObject result = new JSONObject(response); String success = result.getString("success"); Log.i(TAG, "success is" + success); if (success == "true") { Log.i(TAG, result.getString("result")); final JSONObject data = new JSONObject(result.getString("result")); final JSONArray friends = new JSONArray(data.getString("updated")); // == VTiger updated contacts == for (int i = 0; i < friends.length(); i++) { friendList.add(User.valueOf(friends.getJSONObject(i))); } // == Vtiger contacts deleted === String deleted_contacts = data.getString("deleted"); Log.d(TAG, deleted_contacts); Log.d(TAG, deleted_contacts.substring(deleted_contacts.indexOf("["))); List<String> items = Arrays.asList( deleted_contacts.substring(deleted_contacts.indexOf("[") + 1, deleted_contacts.indexOf("]")) .split("\\s*,\\s*")); for (int ii = 0; ii < items.size(); ii++) { Log.d(TAG, items.get(ii)); if (items.get(ii).startsWith("\"4x")) // this is a contact { //Log.d(TAG,"{\"id\":"+items.get(ii)+",\"d\":true,\"contact_no\":1}"); JSONObject item = new JSONObject( "{\"id\":" + items.get(ii) + ",\"d\":true,\"contact_no\":\"CON1\"}"); friendList.add(User.valueOf(item)); } if (items.get(ii).startsWith("\"3x")) // this is an account { //Log.d(TAG,"{\"id\":"+items.get(ii)+",\"d\":true,\"contact_no\":1}"); JSONObject item = new JSONObject( "{\"id\":" + items.get(ii) + ",\"d\":true,\"account_no\":\"ACC1\"}"); friendList.add(User.valueOf(item)); } if (items.get(ii).startsWith("\"2x")) // this is a lead { //Log.d(TAG,"{\"id\":"+items.get(ii)+",\"d\":true,\"contact_no\":1}"); JSONObject item = new JSONObject( "{\"id\":" + items.get(ii) + ",\"d\":true,\"lead_no\":\"LEA1\"}"); friendList.add(User.valueOf(item)); } } } else { LastFetchOperationStatus = false; // FIXME: else false... // possible error code : //{"success":false,"error":{"code":"AUTHENTICATION_REQUIRED","message":"Authencation required"}} // throw new AuthenticationException(); } } else { if (status == HttpURLConnection.HTTP_UNAUTHORIZED) { LastFetchOperationStatus = false; Log.e(TAG, "Authentication exception in fetching remote contacts"); throw new AuthenticationException(); } else { LastFetchOperationStatus = false; Log.e(TAG, "Server error in fetching remote contacts: "); throw new IOException(); } } return friendList; }
From source file:com.webarch.common.net.http.HttpService.java
/** * ?Http/*from www . j ava2 s . c o m*/ * * @param requestUrl ? * @param requestMethod ? * @param outputJson ? * @return */ public static String doHttpRequest(String requestUrl, String requestMethod, String outputJson) { String result = null; try { StringBuffer buffer = new StringBuffer(); URL url = new URL(requestUrl); HttpURLConnection httpUrlConn = (HttpURLConnection) url.openConnection(); httpUrlConn.setDoOutput(true); httpUrlConn.setDoInput(true); httpUrlConn.setUseCaches(false); httpUrlConn.setUseCaches(false); httpUrlConn.setRequestProperty("Accept-Charset", DEFAULT_CHARSET); httpUrlConn.setRequestProperty("Content-Type", "application/json;charset=" + DEFAULT_CHARSET); // ?GET/POST httpUrlConn.setRequestMethod(requestMethod); if ("GET".equalsIgnoreCase(requestMethod)) httpUrlConn.connect(); // ???? if (null != outputJson) { OutputStream outputStream = httpUrlConn.getOutputStream(); //?? outputStream.write(outputJson.getBytes(DEFAULT_CHARSET)); outputStream.close(); } // ??? InputStream inputStream = httpUrlConn.getInputStream(); InputStreamReader inputStreamReader = new InputStreamReader(inputStream, DEFAULT_CHARSET); BufferedReader bufferedReader = new BufferedReader(inputStreamReader); String str = null; while ((str = bufferedReader.readLine()) != null) { buffer.append(str); } result = buffer.toString(); bufferedReader.close(); inputStreamReader.close(); // ? inputStream.close(); httpUrlConn.disconnect(); } catch (ConnectException ce) { logger.error("server connection timed out.", ce); } catch (Exception e) { logger.error("http request error:", e); } finally { return result; } }
From source file:com.mobile.natal.natalchart.NetworkUtilities.java
/** * Sends an HTTP GET request to a url//w ww. j ava 2s . c o m * * @param urlStr - The URL of the server. (Example: " http://www.yahoo.com/search") * @param file the output file. If it is a folder, it tries to get the file name from the header. * @param requestParameters - all the request parameters (Example: "param1=val1¶m2=val2"). * Note: This method will add the question mark (?) to the request - * DO NOT add it yourself * @param user user. * @param password password. * @return the file written. * @throws Exception if something goes wrong. */ public static File sendGetRequest4File(String urlStr, File file, String requestParameters, String user, String password) throws Exception { if (requestParameters != null && requestParameters.length() > 0) { urlStr += "?" + requestParameters; } HttpURLConnection conn = makeNewConnection(urlStr); conn.setRequestMethod("GET"); // conn.setDoOutput(true); conn.setDoInput(true); // conn.setChunkedStreamingMode(0); conn.setUseCaches(false); if (user != null && password != null && user.trim().length() > 0 && password.trim().length() > 0) { conn.setRequestProperty("Authorization", getB64Auth(user, password)); } conn.connect(); if (file.isDirectory()) { // try to get the header String headerField = conn.getHeaderField("Content-Disposition"); String fileName = null; if (headerField != null) { String[] split = headerField.split(";"); for (String string : split) { String pattern = "filename="; if (string.toLowerCase().startsWith(pattern)) { fileName = string.replaceFirst(pattern, ""); break; } } } if (fileName == null) { // give a name fileName = "FILE_" + TimeUtilities.INSTANCE.TIMESTAMPFORMATTER_LOCAL.format(new Date()); } file = new File(file, fileName); } InputStream in = null; FileOutputStream out = null; try { in = conn.getInputStream(); out = new FileOutputStream(file); byte[] buffer = new byte[(int) maxBufferSize]; int bytesRead = in.read(buffer, 0, (int) maxBufferSize); while (bytesRead > 0) { out.write(buffer, 0, bytesRead); bytesRead = in.read(buffer, 0, (int) maxBufferSize); } out.flush(); } finally { if (in != null) in.close(); if (out != null) out.close(); if (conn != null) conn.disconnect(); } return file; }
From source file:edu.stanford.epadd.launcher.Splash.java
private static boolean killRunningServer(String url) throws IOException { try {//w w w . j a v a2 s.com // 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 // actually this should not be a HTTP connection, it can be simply any connection out.println("Sending a kill request to " + url); HttpURLConnection u = (HttpURLConnection) new URL(url).openConnection(); u.connect(); if (u.getResponseCode() == 200) { u.disconnect(); return true; } u.disconnect(); } catch (ConnectException ce) { err.println("Warning: unable to kill running server: " + ce); } return false; }
From source file:br.bireme.tb.URLS.java
/** * Given an url, loads its content (GET - method) * @param url url to be loaded/* w w w . j av a 2s.c om*/ * @return an array with the real location of the page (in case of redirect) * and its content. * @throws IOException */ public static String[] loadPageGet(final URL url) throws IOException { if (url == null) { throw new NullPointerException("url"); } System.out.print("loading page (GET) : [" + url + "]"); HttpURLConnection.setFollowRedirects(false); HttpURLConnection connection = (HttpURLConnection) url.openConnection(); connection.setRequestMethod("GET"); connection.setRequestProperty("Accept-Charset", DEFAULT_ENCODING); connection.setRequestProperty("User-Agent", "curl/7.29.0"); connection.setRequestProperty("Accept", "*/*"); connection.connect(); int respCode = connection.getResponseCode(); final StringBuilder builder = new StringBuilder(); String location = url.toString(); while ((respCode >= 300) && (respCode <= 399)) { location = connection.getHeaderField("Location"); connection = (HttpURLConnection) new URL(location).openConnection(); respCode = connection.getResponseCode(); } final boolean respCodeOk = (respCode == 200); final BufferedReader reader; boolean skipLine = false; if (respCodeOk) { reader = new BufferedReader(new InputStreamReader(connection.getInputStream(), DEFAULT_ENCODING)); } else { reader = new BufferedReader(new InputStreamReader(connection.getErrorStream(), DEFAULT_ENCODING)); } while (true) { String line = reader.readLine(); if (line == null) { break; } final String line2 = line.trim(); if (line2.startsWith("<!--")) { if (line2.endsWith("-->")) { continue; } skipLine = true; } else if (line2.endsWith("-->")) { skipLine = false; line = ""; } if (!skipLine) { builder.append(line); builder.append("\n"); } } reader.close(); connection.disconnect(); if (!respCodeOk) { throw new IOException("url=[" + url + "]\ncode=" + respCode + "\n" + builder.toString()); } //System.out.print("+"); System.out.println(" - OK"); return new String[] { location, builder.toString() }; }
From source file:manchester.synbiochem.datacapture.SeekConnector.java
private static Status postForm(HttpURLConnection c, MultipartFormData form) throws IOException { c.setInstanceFollowRedirects(false); c.setDoOutput(true);//from ww w. j av a 2s.c o m c.setRequestMethod("POST"); c.setRequestProperty("Content-Type", form.contentType()); c.setRequestProperty("Content-Length", form.length()); c.connect(); try (OutputStream os = c.getOutputStream()) { os.write(form.content()); } return fromStatusCode(c.getResponseCode()); }
From source file:com.stockita.popularmovie.utility.Utilities.java
/** * This will make a GET request to a RESTful web. * * @return String of JSON format/*w ww . java 2s . c o m*/ */ public static String getMovieData(String uri, Context context) { BufferedReader reader = null; HttpURLConnection con = null; try { URL url = new URL(uri); con = (HttpURLConnection) url.openConnection(); con.setReadTimeout(10000 /* milliseconds */); con.setConnectTimeout(15000 /* milliseconds */); con.setRequestMethod(REQUEST_METHOD_GET); con.connect(); int response = con.getResponseCode(); if (response < 200 || response > 299) { Log.e(LOG_TAG, "connection failed: " + response); sNetworkResponse = false; return null; } InputStream inputStream = con.getInputStream(); // Return null if no date if (inputStream == null) { Log.e(LOG_TAG, "inputStream returned null"); return null; } reader = new BufferedReader(new InputStreamReader(inputStream)); StringBuilder builder = new StringBuilder(); String line; while ((line = reader.readLine()) != null) { builder.append(line + "\n"); } // Return null if no data if (builder.length() == 0) { Log.e(LOG_TAG, "builder return null"); return null; } return builder.toString(); } catch (IOException e) { Log.e(LOG_TAG, e.toString()); sNetworkResponse = false; return null; } finally { try { if (reader != null) reader.close(); if (con != null) con.disconnect(); } catch (Exception e) { e.printStackTrace(); Log.e(LOG_TAG, e.toString()); } } }
From source file:au.com.tyo.sn.shortener.GooGl.java
private static String post(String url) { HttpURLConnection httpcon = null; try {//ww w . j a v a2 s . c o m httpcon = (HttpURLConnection) ((new URL(GOO_GL_REQUEST_URL).openConnection())); httpcon.setDoOutput(true); httpcon.setRequestProperty("Content-Type", "application/json"); httpcon.setRequestProperty("Accept", "application/json"); httpcon.setRequestMethod("POST"); } catch (MalformedURLException e) { e.printStackTrace(); } catch (IOException e) { e.printStackTrace(); } byte[] outputBytes = { 0 }; OutputStream os = null; InputStream is = null; BufferedReader in = null; StringBuilder text = new StringBuilder(); try { outputBytes = ("{'longUrl': \"" + url + "\"}").getBytes("UTF-8"); httpcon.setRequestProperty("Content-Length", Integer.toString(outputBytes.length)); httpcon.connect(); os = httpcon.getOutputStream(); os.write(outputBytes); is = httpcon.getInputStream(); in = new BufferedReader(new InputStreamReader(is, "UTF-8")); if (in != null) { // get page text String line; while ((line = in.readLine()) != null) { text.append(line); text.append("\n"); } } } catch (UnsupportedEncodingException e) { e.printStackTrace(); } catch (IOException e) { e.printStackTrace(); } finally { try { if (os != null) os.close(); if (is != null) is.close(); if (in != null) in.close(); } catch (IOException e) { } } return text.toString(); }