List of usage examples for java.net HttpURLConnection setReadTimeout
public void setReadTimeout(int timeout)
From source file:com.uksf.mf.core.utility.ClassNames.java
/** * Checks if connection to URL can be established * @param url url to check//from ww w. jav a 2 s . c om * @return connection state * @throws IOException error */ private static boolean checkConnection(URL url) throws IOException { HttpURLConnection connection = (HttpURLConnection) url.openConnection(); connection.setRequestMethod("GET"); connection.setConnectTimeout(1500); connection.setReadTimeout(1500); connection.setRequestProperty("User-Agent", "Mozilla/5.0 (Windows; U; Windows NT 6.0; en-US; rv:1.9.1.2) Gecko/20090729 Firefox/3.5.2 (.NET CLR 3.5.30729)"); connection.connect(); return connection.getResponseCode() == 404; }
From source file:com.adr.raspberryleds.HTTPUtils.java
public static JSONObject execPOST(String address, JSONObject params) throws IOException { BufferedReader readerin = null; Writer writerout = null;//from ww w . j a v a2s . c om try { URL url = new URL(address); String query = params.toString(); HttpURLConnection connection = (HttpURLConnection) url.openConnection(); connection.setReadTimeout(10000 /* milliseconds */); connection.setConnectTimeout(15000 /* milliseconds */); connection.setRequestMethod("POST"); connection.setAllowUserInteraction(false); connection.setUseCaches(false); connection.setDoInput(true); connection.setDoOutput(true); connection.addRequestProperty("Content-Type", "application/json,encoding=UTF-8"); connection.addRequestProperty("Content-length", String.valueOf(query.length())); writerout = new OutputStreamWriter(connection.getOutputStream(), "UTF-8"); writerout.write(query); writerout.flush(); writerout.close(); writerout = null; int responsecode = connection.getResponseCode(); if (responsecode == HttpURLConnection.HTTP_OK) { StringBuilder text = new StringBuilder(); readerin = new BufferedReader(new InputStreamReader(connection.getInputStream(), "UTF-8")); String line = null; while ((line = readerin.readLine()) != null) { text.append(line); text.append(System.getProperty("line.separator")); } JSONObject result = new JSONObject(text.toString()); if (result.has("exception")) { throw new IOException( MessageFormat.format("Remote exception: {0}.", result.getString("exception"))); } else { return result; } } else { throw new IOException(MessageFormat.format("HTTP response error: {0}. {1}", Integer.toString(responsecode), connection.getResponseMessage())); } } catch (JSONException ex) { throw new IOException(MessageFormat.format("Parse exception: {0}.", ex.getMessage())); } finally { if (writerout != null) { writerout.close(); writerout = null; } if (readerin != null) { readerin.close(); readerin = null; } } }
From source file:Main.java
public static String UpdateScore(String userName, int br) { String retStr = ""; try {/*from w w w .j a v a2s.co m*/ URL url = new URL("http://" + IP_ADDRESS + "/RiddleQuizApp/ServerSide/AzurirajHighScore.php"); HttpURLConnection conn = (HttpURLConnection) url.openConnection(); conn.setConnectTimeout(15000); conn.setReadTimeout(10000); conn.setRequestMethod("POST"); conn.setDoInput(true); conn.setDoOutput(true); Log.e("http", "por1"); JSONObject data = new JSONObject(); data.put("username", userName); data.put("broj", br); Log.e("http", "por3"); Uri.Builder builder = new Uri.Builder().appendQueryParameter("action", data.toString()); String query = builder.build().getEncodedQuery(); Log.e("http", "por4"); OutputStream os = conn.getOutputStream(); BufferedWriter bw = new BufferedWriter(new OutputStreamWriter(os, "UTF-8")); bw.write(query); Log.e("http", "por5"); bw.flush(); bw.close(); os.close(); int responseCode = conn.getResponseCode(); Log.e("http", String.valueOf(responseCode)); if (responseCode == HttpURLConnection.HTTP_OK) { retStr = inputStreamToString(conn.getInputStream()); } else retStr = String.valueOf("Error: " + responseCode); Log.e("http", retStr); } catch (Exception e) { Log.e("http", "greska"); } return retStr; }
From source file:Main.java
/** * Downloads a file via HTTP(S) GET to the given path. This function cannot be called from the * UI thread. Android does not allow it. * * @param urlString Url to the ressource to download. * @param file file to be written to. * @param overwrite if file exists, overwrite? * @return flase if download was not successful. If successful, true. *//*from w w w . j a va 2 s .com*/ private static Boolean fileDownloadHttp(String urlString, File file, Boolean overwrite) { HashMap<String, String> result = null; URL url = null; // File temp; try { url = new URL(urlString); HttpURLConnection urlConnection = (HttpURLConnection) url.openConnection(); urlConnection.setRequestMethod("GET"); urlConnection.setReadTimeout(200000); urlConnection.connect(); InputStream in = new BufferedInputStream(urlConnection.getInputStream()); FileOutputStream outputStream = new FileOutputStream(file); int read = 0; byte[] bytes = new byte[1024]; while ((read = in.read(bytes)) != -1) { outputStream.write(bytes, 0, read); } in.close(); outputStream.close(); urlConnection.disconnect(); } catch (MalformedURLException e) { e.printStackTrace(); return false; } catch (IOException e) { e.printStackTrace(); return false; } Log.d(TAG, "File download: " + file.getAbsolutePath() + url.getFile() + "overwrite " + overwrite + "exists? " + file.exists()); return true; }
From source file:Main.java
public static String UdatePlayerBT(String userName, String device) { String retStr = ""; try {//from ww w. j a va2 s. co m URL url = new URL("http://" + IP_ADDRESS + "/RiddleQuizApp/ServerSide/PostaviBTdevice.php"); HttpURLConnection conn = (HttpURLConnection) url.openConnection(); conn.setConnectTimeout(15000); conn.setReadTimeout(10000); conn.setRequestMethod("POST"); conn.setDoInput(true); conn.setDoOutput(true); Log.e("http", "por1"); JSONObject data = new JSONObject(); data.put("username", userName); data.put("bt_device", device); Log.e("http", "por3"); Uri.Builder builder = new Uri.Builder().appendQueryParameter("action", data.toString()); String query = builder.build().getEncodedQuery(); Log.e("http", "por4"); OutputStream os = conn.getOutputStream(); BufferedWriter bw = new BufferedWriter(new OutputStreamWriter(os, "UTF-8")); bw.write(query); Log.e("http", "por5"); bw.flush(); bw.close(); os.close(); int responseCode = conn.getResponseCode(); Log.e("http", String.valueOf(responseCode)); if (responseCode == HttpURLConnection.HTTP_OK) { retStr = inputStreamToString(conn.getInputStream()); } else retStr = String.valueOf("Error: " + responseCode); Log.e("http", retStr); } catch (Exception e) { Log.e("http", "greska"); } return retStr; }
From source file:hudson.Main.java
/** * Connects to the given HTTP URL and configure time out, to avoid infinite hang. *///from w ww. java 2 s . c o m private static HttpURLConnection open(URL url) throws IOException { HttpURLConnection c = (HttpURLConnection) url.openConnection(); c.setReadTimeout(TIMEOUT); c.setConnectTimeout(TIMEOUT); return c; }
From source file:com.alexoree.jenkins.Main.java
private static String download(String localName, String remoteUrl) throws Exception { URL obj = new URL(remoteUrl); HttpURLConnection conn = (HttpURLConnection) obj.openConnection(); conn.setReadTimeout(5000); System.out.println("Request URL ... " + remoteUrl); boolean redirect = false; // normally, 3xx is redirect int status = conn.getResponseCode(); if (status != HttpURLConnection.HTTP_OK) { if (status == HttpURLConnection.HTTP_MOVED_TEMP || status == HttpURLConnection.HTTP_MOVED_PERM || status == HttpURLConnection.HTTP_SEE_OTHER) redirect = true;//w w w .jav a 2 s . co m } if (redirect) { // get redirect url from "location" header field String newUrl = conn.getHeaderField("Location"); // get the cookie if need, for login String cookies = conn.getHeaderField("Set-Cookie"); // open the new connnection again conn = (HttpURLConnection) new URL(newUrl).openConnection(); String version = newUrl.substring(newUrl.lastIndexOf("/", newUrl.lastIndexOf("/") - 1) + 1, newUrl.lastIndexOf("/")); String pluginname = localName.substring(localName.lastIndexOf("/") + 1); String ext = ""; if (pluginname.endsWith(".war")) ext = ".war"; else ext = ".hpi"; pluginname = pluginname.replace(ext, ""); localName = localName.replace(pluginname + ext, "/download/plugins/" + pluginname + "/" + version + "/"); new File(localName).mkdirs(); localName += pluginname + ext; System.out.println("Redirect to URL : " + newUrl); } if (new File(localName).exists()) { System.out.println(localName + " exists, skipping"); return localName; } byte[] buffer = new byte[2048]; FileOutputStream baos = new FileOutputStream(localName); InputStream inputStream = conn.getInputStream(); int totalBytes = 0; int read = inputStream.read(buffer); while (read > 0) { totalBytes += read; baos.write(buffer, 0, read); read = inputStream.read(buffer); } System.out.println("Retrieved " + totalBytes + "bytes"); return localName; }
From source file:Main.java
public static String readTextFromURL(String urlString) throws IOException { HttpURLConnection urlConnection = null; URL url = new URL(urlString); urlConnection = (HttpURLConnection) url.openConnection(); urlConnection.setRequestMethod("GET"); urlConnection.setReadTimeout(10000 /* milliseconds */); urlConnection.setConnectTimeout(15000 /* milliseconds */); urlConnection.setDoOutput(true);// ww w. ja v a 2s .co m urlConnection.connect(); BufferedReader br = new BufferedReader(new InputStreamReader(url.openStream())); char[] buffer = new char[1024]; String jsonString = new String(); StringBuilder sb = new StringBuilder(); String line; while ((line = br.readLine()) != null) { sb.append(line + "\n"); } br.close(); return sb.toString(); }
From source file:Main.java
/** * Make an HTTP request to the given URL and return a String as the response. */// w ww. java 2 s . com private static String makeHttpRequest(URL url) throws IOException { String jsonResponse = ""; // If the URL is null, then return early. if (url == null) { return jsonResponse; } HttpURLConnection urlConnection = null; InputStream inputStream = null; try { urlConnection = (HttpURLConnection) url.openConnection(); urlConnection.setReadTimeout(10000 /* milliseconds */); urlConnection.setConnectTimeout(15000 /* milliseconds */); urlConnection.setRequestMethod("GET"); urlConnection.connect(); /* If the request was successful (response code 200), then read the input stream and parse the response. */ if (urlConnection.getResponseCode() == 200) { inputStream = urlConnection.getInputStream(); jsonResponse = readFromStream(inputStream); } else { //handle exception } } catch (IOException e) { //handle exception } finally { if (urlConnection != null) { urlConnection.disconnect(); } if (inputStream != null) { inputStream.close(); } } return jsonResponse; }
From source file:edu.xjtu.qxcamerabridge.LiveviewImageExtractor.java
private static InputStream getLiveviewInputStream(String liveviewURL) throws MalformedURLException, IOException { URL url = new URL(liveviewURL); HttpURLConnection connection = (HttpURLConnection) url.openConnection(); connection.setRequestMethod("GET"); connection.setReadTimeout(2000); connection.connect();//from w w w . j av a2 s . co m if (connection.getResponseCode() == HttpURLConnection.HTTP_OK) { return connection.getInputStream(); } return null; }