List of usage examples for java.net HttpURLConnection setConnectTimeout
public void setConnectTimeout(int timeout)
From source file:fr.mixit.android.utils.NetworkUtils.java
@TargetApi(Build.VERSION_CODES.GINGERBREAD) static ResponseHttp getInputStreamFromHttpUrlConnection(String url, boolean isPost, String args) { final ResponseHttp myResponse = new ResponseHttp(); HttpURLConnection urlConnection = null; if (cookieManager == null) { cookieManager = new CookieManager(); CookieHandler.setDefault(cookieManager); }//from ww w .j a v a 2 s.c o m try { String urlWithParams = url; if (!isPost && args != null) { urlWithParams = getGetURL(url, args); } final URL urlObject = new URL(urlWithParams); urlConnection = (HttpURLConnection) urlObject.openConnection(); urlConnection.setConnectTimeout(CONNECTION_TIMEOUT); urlConnection.setReadTimeout(SOCKET_TIMEOUT); // if (cookieSession != null) { // cookieManager.getCookieStore().removeAll(); // cookieManager.getCookieStore().addCookie(cookieSession); // } if (isPost) { urlConnection.setDoOutput(true); } // urlConnection.connect(); if (isPost && args != null) { final byte[] params = args.getBytes(HTTP.UTF_8); urlConnection.setFixedLengthStreamingMode(params.length);// or urlConnection.setChunkedStreamingMode(0); final OutputStream out = new BufferedOutputStream(urlConnection.getOutputStream()); out.write(params); } myResponse.status = urlConnection.getResponseCode(); if (DEBUG_MODE) { Log.d(TAG, "Status code : " + myResponse.status); } myResponse.jsonText = getJson(urlConnection.getInputStream()); } catch (final MalformedURLException e) { if (DEBUG_MODE) { Log.e(TAG, "The URL is malformatted", e); } } catch (final IllegalAccessError e) { if (DEBUG_MODE) { Log.e(TAG, "setDoOutput after openning a connection or already done"); } } catch (final UnsupportedEncodingException e) { if (DEBUG_MODE) { Log.e(TAG, "UTF8 unsupported for args", e); } } catch (final IllegalStateException e) { if (DEBUG_MODE) { Log.e(TAG, "I/O Error", e); } } catch (final IllegalArgumentException e) { if (DEBUG_MODE) { Log.e(TAG, "I/O Error", e); } } catch (final IOException e) { if (DEBUG_MODE) { Log.e(TAG, "I/O Error", e); } } finally { if (urlConnection != null) { urlConnection.disconnect(); } } return myResponse; }
From source file:com.dopecoin.wallet.ExchangeRatesProvider.java
private static float requestDogeBtcConversion(int provider) { HttpURLConnection connection = null; Reader reader = null;//from www .j a v a 2s . c o m URL providerUrl; switch (provider) { case 0: providerUrl = DOPEPOOL_URL; break; case 1: providerUrl = VIRCUREX_URL; break; default: providerUrl = DOPEPOOL_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("DOPE") .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:in.leafco.wallet.ExchangeRatesProvider.java
private static float requestDogeBtcConversion(int provider) { HttpURLConnection connection = null; Reader reader = null;/* w w w . j a v 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 www. j a v a 2 s . 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.zzl.zl_app.cache.Utility.java
public static String uploadFile(File file, String RequestURL, String fileName) { Tools.log("IO", "RequestURL:" + RequestURL); String result = null;/*from w w w . j av a2 s. c om*/ String BOUNDARY = UUID.randomUUID().toString(); // ?? String PREFIX = "--", LINE_END = "\r\n"; String CONTENT_TYPE = "multipart/form-data"; // try { URL url = new URL(RequestURL); HttpURLConnection conn = (HttpURLConnection) url.openConnection(); conn.setReadTimeout(Utility.SET_SOCKET_TIMEOUT); conn.setConnectTimeout(Utility.SET_CONNECTION_TIMEOUT); conn.setDoInput(true); // ?? conn.setDoOutput(true); // ?? conn.setUseCaches(false); // ?? conn.setRequestMethod("POST"); // ? conn.setRequestProperty("Charset", CHARSET); // ? conn.setRequestProperty("connection", "keep-alive"); conn.setRequestProperty("Content-Type", CONTENT_TYPE + ";boundary=" + BOUNDARY); if (file != null) { /** * ? */ DataOutputStream dos = new DataOutputStream(conn.getOutputStream()); StringBuffer sb = new StringBuffer(); sb.append(PREFIX); sb.append(BOUNDARY); sb.append(LINE_END); /** * ?? name???key ?key ?? * filename?????? :abc.png */ sb.append("Content-Disposition: form-data; name=\"voice\"; filename=\"" + file.getName() + "\"" + LINE_END); sb.append("Content-Type: application/octet-stream; charset=" + CHARSET + LINE_END); sb.append(LINE_END); dos.write(sb.toString().getBytes()); Tools.log("FileSize", "file:" + file.length()); InputStream is = new FileInputStream(file); byte[] bytes = new byte[1024]; int len = 0; while ((len = is.read(bytes)) != -1) { dos.write(bytes, 0, len); Tools.log("FileSize", "size:" + len); } dos.write(LINE_END.getBytes()); byte[] end_data = (PREFIX + BOUNDARY + PREFIX + LINE_END).getBytes(); dos.write(end_data); dos.flush(); dos.close(); is.close(); /** * ??? 200=? ????? */ int res = conn.getResponseCode(); Tools.log("IO", "ResponseCode:" + res); if (res == 200) { InputStream input = conn.getInputStream(); StringBuffer sb1 = new StringBuffer(); int ss; while ((ss = input.read()) != -1) { sb1.append((char) ss); } result = sb1.toString(); } } } catch (MalformedURLException e) { e.printStackTrace(); } catch (IOException e) { e.printStackTrace(); } return result; }
From source file:com.apptentive.android.sdk.comm.ApptentiveClient.java
private static ApptentiveHttpResponse performMultipartFilePost(Context context, String oauthToken, String uri, String postBody, StoredFile storedFile) { Log.d("Performing multipart request to %s", uri); ApptentiveHttpResponse ret = new ApptentiveHttpResponse(); if (storedFile == null) { Log.e("StoredFile is null. Unable to send."); return ret; }//from w ww . java 2 s.c om int bytesRead; int bufferSize = 4096; byte[] buffer; String lineEnd = "\r\n"; String twoHyphens = "--"; String boundary = UUID.randomUUID().toString(); HttpURLConnection connection; DataOutputStream os = null; InputStream is = null; try { is = context.openFileInput(storedFile.getLocalFilePath()); // Set up the request. URL url = new URL(uri); connection = (HttpURLConnection) url.openConnection(); connection.setDoInput(true); connection.setDoOutput(true); connection.setUseCaches(false); connection.setConnectTimeout(DEFAULT_HTTP_CONNECT_TIMEOUT); connection.setReadTimeout(DEFAULT_HTTP_SOCKET_TIMEOUT); connection.setRequestMethod("POST"); connection.setRequestProperty("Connection", "Keep-Alive"); connection.setRequestProperty("Content-Type", "multipart/form-data;boundary=" + boundary); connection.setRequestProperty("Authorization", "OAuth " + oauthToken); connection.setRequestProperty("Accept", "application/json"); connection.setRequestProperty("X-API-Version", API_VERSION); connection.setRequestProperty("User-Agent", getUserAgentString()); StringBuilder requestText = new StringBuilder(); // Write form data requestText.append(twoHyphens).append(boundary).append(lineEnd); requestText.append("Content-Disposition: form-data; name=\"message\"").append(lineEnd); requestText.append("Content-Type: text/plain").append(lineEnd); requestText.append(lineEnd); requestText.append(postBody); requestText.append(lineEnd); // Write file attributes. requestText.append(twoHyphens).append(boundary).append(lineEnd); requestText.append(String.format("Content-Disposition: form-data; name=\"file\"; filename=\"%s\"", storedFile.getFileName())).append(lineEnd); requestText.append("Content-Type: ").append(storedFile.getMimeType()).append(lineEnd); requestText.append(lineEnd); Log.d("Post body: " + requestText); // Open an output stream. os = new DataOutputStream(connection.getOutputStream()); // Write the text so far. os.writeBytes(requestText.toString()); try { // Write the actual file. buffer = new byte[bufferSize]; while ((bytesRead = is.read(buffer, 0, bufferSize)) > 0) { os.write(buffer, 0, bytesRead); } } catch (IOException e) { Log.d("Error writing file bytes to HTTP connection.", e); ret.setBadPayload(true); throw e; } os.writeBytes(twoHyphens + boundary + twoHyphens + lineEnd); os.close(); ret.setCode(connection.getResponseCode()); ret.setReason(connection.getResponseMessage()); // TODO: These streams may not be ready to read now. Put this in a new thread. // Read the normal response. InputStream nis = null; ByteArrayOutputStream nbaos = null; try { Log.d("Sending file: " + storedFile.getLocalFilePath()); nis = connection.getInputStream(); nbaos = new ByteArrayOutputStream(); byte[] eBuf = new byte[1024]; int eRead; while (nis != null && (eRead = nis.read(eBuf, 0, 1024)) > 0) { nbaos.write(eBuf, 0, eRead); } ret.setContent(nbaos.toString()); } catch (IOException e) { Log.w("Can't read return stream.", e); } finally { Util.ensureClosed(nis); Util.ensureClosed(nbaos); } // Read the error response. InputStream eis = null; ByteArrayOutputStream ebaos = null; try { eis = connection.getErrorStream(); ebaos = new ByteArrayOutputStream(); byte[] eBuf = new byte[1024]; int eRead; while (eis != null && (eRead = eis.read(eBuf, 0, 1024)) > 0) { ebaos.write(eBuf, 0, eRead); } if (ebaos.size() > 0) { ret.setContent(ebaos.toString()); } } catch (IOException e) { Log.w("Can't read error stream.", e); } finally { Util.ensureClosed(eis); Util.ensureClosed(ebaos); } Log.d("HTTP " + connection.getResponseCode() + ": " + connection.getResponseMessage() + ""); Log.v(ret.getContent()); } catch (FileNotFoundException e) { Log.e("Error getting file to upload.", e); } catch (MalformedURLException e) { Log.e("Error constructing url for file upload.", e); } catch (SocketTimeoutException e) { Log.w("Timeout communicating with server."); } catch (IOException e) { Log.e("Error executing file upload.", e); } finally { Util.ensureClosed(is); Util.ensureClosed(os); } return ret; }
From source file:com.screenslicer.common.CommonUtil.java
public static void postQuickly(String uri, String recipient, String postData) { HttpURLConnection conn = null; try {//from ww w .ja v a2 s .c o m postData = Crypto.encode(postData, recipient); conn = (HttpURLConnection) new URL(uri).openConnection(); conn.setDoOutput(true); conn.setUseCaches(false); conn.setRequestMethod("POST"); conn.setConnectTimeout(5000); conn.setReadTimeout(5000); conn.setRequestProperty("Content-Type", "application/json"); byte[] bytes = postData.getBytes("utf-8"); conn.setRequestProperty("Content-Length", String.valueOf(bytes.length)); OutputStream os = conn.getOutputStream(); os.write(bytes); conn.connect(); Crypto.decode(IOUtils.toString(conn.getInputStream(), "utf-8"), recipient); } catch (Exception e) { Log.exception(e); } }
From source file:de.langerhans.wallet.ExchangeRatesProvider.java
private static double requestDogeBtcConversion(int provider) { HttpURLConnection connection = null; Reader reader = null;//from w w w .j a v a2 s .c o m URL providerUrl; switch (provider) { case 0: providerUrl = CRYPTSY_URL; break; case 1: providerUrl = BTER_URL; break; default: providerUrl = CRYPTSY_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)); final StringBuilder content = new StringBuilder(); Io.copy(reader, content); try { final JSONObject json = new JSONObject(content.toString()); double rate; boolean success; switch (provider) { case 0: success = json.getBoolean("success"); if (!success) { return -1; } rate = json.getJSONObject("data").getJSONObject("last_trade").getDouble("price"); break; case 1: success = json.getString("result").equals("true"); // Eww bad API! if (!success) { return -1; } rate = Double.valueOf(json.getString("last")); 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.screenslicer.common.CommonUtil.java
public static String post(String uri, String recipient, String postData) { HttpURLConnection conn = null; try {// ww w . j a va 2 s . c o m postData = Crypto.encode(postData, recipient); conn = (HttpURLConnection) new URL(uri).openConnection(); conn.setDoOutput(true); conn.setUseCaches(false); conn.setRequestMethod("POST"); conn.setConnectTimeout(0); conn.setRequestProperty("Content-Type", "application/json"); byte[] bytes = postData.getBytes("utf-8"); conn.setRequestProperty("Content-Length", String.valueOf(bytes.length)); OutputStream os = conn.getOutputStream(); os.write(bytes); conn.connect(); if (conn.getResponseCode() == 205) { return NOT_BUSY; } if (conn.getResponseCode() == 423) { return BUSY; } return Crypto.decode(IOUtils.toString(conn.getInputStream(), "utf-8"), recipient); } catch (Exception e) { Log.exception(e); } return ""; }
From source file:com.stockita.popularmovie.utility.Utilities.java
/** * This will make a GET request to a RESTful web. * * @return String of JSON format//from w w w .j ava 2 s . 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()); } } }