List of usage examples for java.net HttpURLConnection setConnectTimeout
public void setConnectTimeout(int timeout)
From source file:hudson.Main.java
/** * Connects to the given HTTP URL and configure time out, to avoid infinite hang. *//*from w w w.jav a2 s . co 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:Main.java
static public JSONArray loadJSON(String url) { HttpURLConnection connection = null; JSONArray json = null;/*from w w w .j a va 2 s . c o m*/ InputStream is = null; try { connection = (HttpURLConnection) new URL(url).openConnection(); connection.setConnectTimeout(5000); is = new BufferedInputStream(connection.getInputStream()); json = new JSONArray(convertStreamToString(is)); } catch (IOException ioe) { ioe.printStackTrace(); } catch (JSONException je) { je.printStackTrace(); } finally { try { if (is != null) { is.close(); } } catch (IOException ioe) { ioe.printStackTrace(); } if (connection != null) { connection.disconnect(); } } return json; }
From source file:com.ibuildapp.romanblack.CataloguePlugin.imageloader.Utils.java
public static String downloadFile(Context context, String url, String md5) { final int BYTE_ARRAY_SIZE = 8024; final int CONNECTION_TIMEOUT = 30000; final int READ_TIMEOUT = 30000; try {/* w w w . j a va 2 s . co m*/ for (int i = 0; i < 3; i++) { URL fileUrl = new URL(URLDecoder.decode(url)); HttpURLConnection connection = (HttpURLConnection) fileUrl.openConnection(); connection.setConnectTimeout(CONNECTION_TIMEOUT); connection.setReadTimeout(READ_TIMEOUT); connection.connect(); int status = connection.getResponseCode(); if (status >= HttpStatus.SC_BAD_REQUEST) { connection.disconnect(); continue; } BufferedInputStream bufferedInputStream = new BufferedInputStream(connection.getInputStream()); File file = new File(StaticData.getCachePath(context) + md5); if (!file.exists()) { new File(StaticData.getCachePath(context)).mkdirs(); file.createNewFile(); } FileOutputStream fileOutputStream = new FileOutputStream(file, false); int byteCount; byte[] buffer = new byte[BYTE_ARRAY_SIZE]; while ((byteCount = bufferedInputStream.read(buffer, 0, BYTE_ARRAY_SIZE)) != -1) fileOutputStream.write(buffer, 0, byteCount); bufferedInputStream.close(); fileOutputStream.flush(); fileOutputStream.close(); return file.getAbsolutePath(); } } catch (Exception e) { e.printStackTrace(); return null; } return null; }
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 w ww . ja v a 2s . 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 readPeopleData(String uri) { URL url;/*from w ww . j a va2 s . c o m*/ StringBuffer jsonstring = null; HttpURLConnection connection; Logger.getAnonymousLogger().info("Getting data for " + uri); try { url = new URL(uri); connection = (HttpURLConnection) url.openConnection(); connection.setConnectTimeout(1000 * 5); InputStreamReader is = new InputStreamReader(connection.getInputStream()); BufferedReader buff = new BufferedReader(is); jsonstring = new StringBuffer(); String line = ""; do { line = buff.readLine(); if (line != null) jsonstring.append(line); } while (line != null); } catch (MalformedURLException e) { // TODO Auto-generated catch block e.printStackTrace(); } catch (IOException e) { // TODO Auto-generated catch block e.printStackTrace(); } Logger.getAnonymousLogger().info("Returning Data " + jsonstring); if (null != jsonstring) { return jsonstring.toString().trim(); } else { return null; } }
From source file:info.tongrenlu.android.helper.HttpHelper.java
static public JSONObject loadJSON(String url) { HttpURLConnection connection = null; JSONObject json = null;/*from w ww . jav a 2 s . co m*/ InputStream is = null; try { connection = (HttpURLConnection) new URL(url).openConnection(); connection.setConnectTimeout(5000); is = new BufferedInputStream(connection.getInputStream()); json = new JSONObject(convertStreamToString(is)); } catch (IOException ioe) { ioe.printStackTrace(); } catch (JSONException je) { je.printStackTrace(); } finally { try { if (is != null) { is.close(); } } catch (IOException ioe) { ioe.printStackTrace(); } if (connection != null) { connection.disconnect(); } } return json; }
From source file:com.melniqw.instagramsdk.Network.java
private static String sendDummyRequest(String url, String body, Request request) throws IOException { HttpURLConnection connection = null; try {// w w w .j a v a 2 s . c o m connection = (HttpURLConnection) new URL(url).openConnection(); connection.setConnectTimeout(10000); connection.setReadTimeout(10000); connection.setUseCaches(false); connection.setDoInput(true); // connection.setRequestProperty("Content-Type", "text/plain; charset=utf-8"); if (request == Request.GET) { connection.setDoOutput(false); connection.setRequestMethod("GET"); } else if (request == Request.POST) { connection.setDoOutput(true); connection.setRequestMethod("POST"); } if (REQUEST_ENABLE_COMPRESSION) connection.setRequestProperty("Accept-Encoding", "gzip"); if (request == Request.POST) connection.getOutputStream().write(body.getBytes("utf-8")); int code = connection.getResponseCode(); System.out.println(TAG + " responseCode = " + code); //It may happen due to keep-alive problem http://stackoverflow.com/questions/1440957/httpurlconnection-getresponsecode-returns-1-on-second-invocation if (code == -1) throw new WrongResponseCodeException("Network error"); // ? 200 //on error can also read error stream from connection. InputStream inputStream = new BufferedInputStream(connection.getInputStream(), 8192); String encoding = connection.getHeaderField("Content-Encoding"); if (encoding != null && encoding.equalsIgnoreCase("gzip")) inputStream = new GZIPInputStream(inputStream); String response = Utils.convertStreamToString(inputStream); System.out.println(TAG + " response = " + response); return response; } finally { if (connection != null) connection.disconnect(); } }
From source file:com.intellij.lang.jsgraphql.languageservice.JSGraphQLNodeLanguageServiceClient.java
private static <R> R executeRequest(Request request, Class<R> responseClass, @NotNull Project project, boolean setProjectDir) { URL url = getJSGraphQLNodeLanguageServiceInstance(project, setProjectDir); if (url == null) { return null; }//from w w w. j av a2 s .co m HttpURLConnection httpConnection = null; try { httpConnection = (HttpURLConnection) url.openConnection(); httpConnection.setConnectTimeout(50); httpConnection.setReadTimeout(1000); httpConnection.setRequestMethod("POST"); httpConnection.setDoOutput(true); httpConnection.setRequestProperty("Content-Type", "application/json"); httpConnection.connect(); try (OutputStreamWriter writer = new OutputStreamWriter(httpConnection.getOutputStream())) { final String jsonRequest = new Gson().toJson(request); writer.write(jsonRequest); writer.flush(); writer.close(); } if (httpConnection.getResponseCode() == 200) { if (responseClass == null) { return null; } try (InputStream inputStream = httpConnection.getInputStream()) { String jsonResponse = IOUtils.toString(inputStream, "UTF-8"); R response = new Gson().fromJson(jsonResponse, responseClass); return response; } } else { log.warn("Got error from JS GraphQL Language Service: HTTP " + httpConnection.getResponseCode() + ": " + httpConnection.getResponseMessage()); } } catch (IOException e) { log.warn("Unable to connect to dev server", e); } finally { if (httpConnection != null) { httpConnection.disconnect(); } } return null; }
From source file:com.mingsoft.weixin.http.HttpClientConnectionManager.java
/** * ?/*from w w w.j a v a 2 s.co m*/ * @param postUrl ? * @param param ? * @param method * @return null */ public static String request(String postUrl, String param, String method) { URL url; try { url = new URL(postUrl); HttpURLConnection conn; conn = (HttpURLConnection) url.openConnection(); conn.setConnectTimeout(30000); // ??) conn.setReadTimeout(30000); // ????) conn.setDoOutput(true); // post??http?truefalse conn.setDoInput(true); // ?httpUrlConnectiontrue conn.setUseCaches(false); // Post ? conn.setRequestProperty("Content-Type", "application/x-www-form-urlencoded"); conn.setRequestMethod(method);// "POST"GET conn.setRequestProperty("Content-Length", param.length() + ""); String encode = "utf-8"; OutputStreamWriter out = null; out = new OutputStreamWriter(conn.getOutputStream(), encode); out.write(param); out.flush(); if (conn.getResponseCode() != HttpURLConnection.HTTP_OK) { return null; } // ?? BufferedReader in = new BufferedReader(new InputStreamReader(conn.getInputStream(), "UTF-8")); String line = ""; StringBuffer strBuf = new StringBuffer(); while ((line = in.readLine()) != null) { strBuf.append(line).append("\n"); } in.close(); out.close(); return strBuf.toString(); } catch (MalformedURLException e2) { // TODO Auto-generated catch block e2.printStackTrace(); } catch (UnsupportedEncodingException e) { // TODO Auto-generated catch block e.printStackTrace(); } catch (IOException e) { // TODO Auto-generated catch block e.printStackTrace(); } return null; }
From source file:net.daporkchop.porkselfbot.util.HTTPUtils.java
public static HttpURLConnection createUrlConnection(final URL url) throws IOException { Validate.notNull(url);/*from ww w . j a v a 2s.co m*/ final HttpURLConnection connection = (HttpURLConnection) url.openConnection(); connection.setConnectTimeout(15000); connection.setReadTimeout(15000); connection.setUseCaches(false); return connection; }