List of usage examples for java.net SocketTimeoutException toString
public String toString()
From source file:give_me_coins.dashboard.JSONHelper.java
private static JSONObject getJSONFromUrl(URL para_url) { // ProgressDialog oShowProgress = ProgressDialog.show(oAct, "Loading", "Loading", true, false); JSONObject oRetJson = null;//w ww . j a v a2 s . c o m try { //Log.d(TAG,para_url.toString()); BufferedInputStream oInput = null; HttpsURLConnection oConnection = (HttpsURLConnection) para_url.openConnection(); // HttpsURLConnection.setDefaultHostnameVerifier(org.apache.http.conn.ssl.SSLSocketFactory.ALLOW_ALL_HOSTNAME_VERIFIER); oConnection.setConnectTimeout(iConnectionTimeout); oConnection.setReadTimeout(iConnectionTimeout * 2); // connection.setRequestProperty ("Authorization", sAuthorization); oConnection.connect(); oInput = new BufferedInputStream(oConnection.getInputStream()); BufferedReader reader = new BufferedReader(new InputStreamReader(oInput)); String sReturn = reader.readLine(); //Log.d(TAG,sReturn); oRetJson = new JSONObject(sReturn); } catch (SocketTimeoutException e) { Log.d(TAG, "Timeout"); } catch (IOException e) { Log.e(TAG, e.toString()); } catch (JSONException e) { Log.e(TAG, e.toString()); } catch (Exception e) { Log.e(TAG, e.toString()); } //para_ProgressDialog.dismiss(); return oRetJson; }
From source file:com.android.utility.util.Network.java
public static boolean isReachable(String url_string) { boolean result = false; try {//from ww w . j ava 2s .c o m HttpGet request = new HttpGet(url_string); HttpParams httpParameters = new BasicHttpParams(); HttpConnectionParams.setConnectionTimeout(httpParameters, 3000); HttpClient httpClient = new DefaultHttpClient(httpParameters); HttpResponse response = httpClient.execute(request); int status = response.getStatusLine().getStatusCode(); if (status == HttpStatus.SC_OK) { result = true; } } catch (SocketTimeoutException e) { result = false; // this is somewhat expected } catch (ClientProtocolException e) { // TODO Auto-generated catch block Logger.e(LogModule.NETWORK, TAG, e.getMessage()); result = false; } catch (IOException e) { // TODO Auto-generated catch block Logger.e(LogModule.NETWORK, TAG, e.toString()); result = false; } return result; }
From source file:org.opendatakit.aggregate.servlet.EnketoApiHandlerServlet.java
protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException { String enketo_api_url = null; HttpURLConnection con = null; BufferedReader in = null;/*from ww w. ja va2 s. c o m*/ String message = null; String enketoURL = null; try { enketo_api_url = req.getParameter("enketo_api_url"); String enketo_api_token = req.getParameter("enketo_api_token"); String form_id = req.getParameter("form_id"); CallingContext cc = ContextFactory.getCallingContext(this, req); String aggregate_server_url = cc.getSecureServerURL(); enketo_api_token += ":"; byte[] encoded = Base64.encodeBase64(enketo_api_token.getBytes()); String urlParameters = "server_url=" + aggregate_server_url + "&form_id=" + form_id; URL obj = new URL(enketo_api_url); con = (HttpURLConnection) obj.openConnection(); con.setRequestMethod("POST"); con.setRequestProperty("Authorization", "Basic " + new String(encoded)); con.setRequestProperty("User-Agent", USER_AGENT); con.setRequestProperty("Accept", "*/*"); con.setRequestProperty("Accept-Charset", "UTF-8"); con.setRequestProperty("Accept-Language", "en-US,en;q=0.5"); // Send post request con.setDoOutput(true); DataOutputStream wr = new DataOutputStream(con.getOutputStream()); wr.writeBytes(urlParameters); wr.flush(); wr.close(); int responseCode = con.getResponseCode(); logger.info("Enketo API response code : " + responseCode); try { in = new BufferedReader(new InputStreamReader(con.getInputStream())); logger.info("Getting the Enketo URL from InputStream"); } catch (Exception io) { in = new BufferedReader(new InputStreamReader(con.getErrorStream())); logger.info("Getting the Error Message from ErrorStream"); } String inputLine = null; StringBuffer response = new StringBuffer(); String responseURL = null; logger.info("BufferReader Object : " + in); if (in != null) { logger.info("BufferReader Object : Not Null "); while ((inputLine = in.readLine()) != null) { if (inputLine.contains("message")) { message = inputLine; System.out.println(message); } if (inputLine.contains("https")) { responseURL = inputLine; } else if (inputLine.contains("http")) { logger.error("Enketo api token is compromised! Enketo URL should specify https"); responseURL = inputLine; } response.append(inputLine); } in.close(); } if (message != null) { String messageArry[] = message.split("\""); if (messageArry.length >= 3) message = messageArry[3]; resp.setStatus(412); resp.setHeader("error", "There was an error obtaining the webform. (message:" + message + ")"); } else if (responseURL != null) { String arryResponseURL[] = responseURL.toString().split(" "); for (String token : arryResponseURL) { if (!token.contains("http")) { continue; } token = token.replace("\\", ""); token = token.replace("\"", ""); token = token.replace(",", ""); enketoURL = token; } resp.setStatus(responseCode); resp.setHeader("enketo_url", enketoURL); logger.info("Enketo API response URL :" + enketoURL); } else { resp.setStatus(responseCode); } } catch (java.net.SocketTimeoutException socketTimeoutException) { logger.info("Exception caught while calling enketo api :" + socketTimeoutException.toString()); resp.setStatus(412); resp.setHeader("error", "API at " + enketo_api_url + " is not available"); } catch (Exception exception) { logger.info("Exception caught while calling enketo api :" + exception.toString()); resp.setStatus(412); if (message == null || message.equals("")) { message = RESPONSE_ERROR; } resp.setHeader("error", "There was an error obtaining the webform. (message:" + message + ")"); } finally { if (con != null) con.disconnect(); } }
From source file:us.mn.state.health.lims.common.externalLinks.ExternalPatientSearch.java
protected void doSearch() { HttpClient httpclient = new DefaultHttpClient(); setTimeout(httpclient);/* w w w . j a va 2s. co m*/ HttpGet httpget = new HttpGet(connectionString); URI getUri = buildConnectionString(httpget.getURI()); httpget.setURI(getUri); try { // Ignore hostname mismatches and allow trust of self-signed certs SSLSocketFactory sslsf = new SSLSocketFactory(new TrustSelfSignedStrategy(), SSLSocketFactory.ALLOW_ALL_HOSTNAME_VERIFIER); Scheme https = new Scheme("https", 443, sslsf); ClientConnectionManager ccm = httpclient.getConnectionManager(); ccm.getSchemeRegistry().register(https); HttpResponse getResponse = httpclient.execute(httpget); returnStatus = getResponse.getStatusLine().getStatusCode(); setPossibleErrors(); setResults(IOUtils.toString(getResponse.getEntity().getContent(), "UTF-8")); } catch (SocketTimeoutException e) { errors.add("Response from patient information server took too long."); LogEvent.logError("ExternalPatientSearch", "doSearch()", e.toString()); // System.out.println("Tinny time out" + e); } catch (ConnectException e) { errors.add("Unable to connect to patient information form service. Service may not be running"); LogEvent.logError("ExternalPatientSearch", "doSearch()", e.toString()); // System.out.println("you no talks? " + e); } catch (IOException e) { errors.add("IO error trying to read input stream."); LogEvent.logError("ExternalPatientSearch", "doSearch()", e.toString()); // System.out.println("all else failed " + e); } catch (KeyManagementException e) { errors.add("Key management error trying to connect to external search service."); LogEvent.logError("ExternalPatientSearch", "doSearch()", e.toString()); } catch (UnrecoverableKeyException e) { errors.add("Unrecoverable key error trying to connect to external search service."); LogEvent.logError("ExternalPatientSearch", "doSearch()", e.toString()); } catch (NoSuchAlgorithmException e) { errors.add("No such encyrption algorithm error trying to connect to external search service."); LogEvent.logError("ExternalPatientSearch", "doSearch()", e.toString()); } catch (KeyStoreException e) { errors.add("Keystore error trying to connect to external search service."); LogEvent.logError("ExternalPatientSearch", "doSearch()", e.toString()); } catch (RuntimeException e) { errors.add("Runtime error trying to retrieve patient information."); LogEvent.logError("ExternalPatientSearch", "doSearch()", e.toString()); httpget.abort(); throw e; } finally { httpclient.getConnectionManager().shutdown(); } }
From source file:org.cerberus.service.rest.impl.RestService.java
@Override public AnswerItem<AppService> callREST(String servicePath, String requestString, String method, List<AppServiceHeader> headerList, List<AppServiceContent> contentList, String token, int timeOutMs) { AnswerItem result = new AnswerItem(); AppService serviceREST = factoryAppService.create("", AppService.TYPE_REST, method, "", "", "", "", "", "", "", "", null, "", null); MessageEvent message = null;/*from ww w. ja v a 2 s . co m*/ if (StringUtils.isNullOrEmpty(servicePath)) { message = new MessageEvent(MessageEventEnum.ACTION_FAILED_CALLSERVICE_SERVICEPATHMISSING); result.setResultMessage(message); return result; } if (StringUtils.isNullOrEmpty(method)) { message = new MessageEvent(MessageEventEnum.ACTION_FAILED_CALLSERVICE_METHODMISSING); result.setResultMessage(message); return result; } // If token is defined, we add 'cerberus-token' on the http header. if (token != null) { headerList.add( factoryAppServiceHeader.create(null, "cerberus-token", token, "Y", 0, "", "", null, "", null)); } CloseableHttpClient httpclient; httpclient = HttpClients.createDefault(); try { // Timeout setup. RequestConfig requestConfig = RequestConfig.custom().setConnectTimeout(timeOutMs).build(); AppService responseHttp = null; switch (method) { case AppService.METHOD_HTTPGET: LOG.info("Start preparing the REST Call (GET). " + servicePath + " - " + requestString); servicePath = StringUtil.addQueryString(servicePath, requestString); serviceREST.setServicePath(servicePath); HttpGet httpGet = new HttpGet(servicePath); // Timeout setup. httpGet.setConfig(requestConfig); // Header. for (AppServiceHeader contentHeader : headerList) { httpGet.addHeader(contentHeader.getKey(), contentHeader.getValue()); } serviceREST.setHeaderList(headerList); // Saving the service before the call Just in case it goes wrong (ex : timeout). result.setItem(serviceREST); LOG.info("Executing request " + httpGet.getRequestLine()); responseHttp = executeHTTPCall(httpclient, httpGet); if (responseHttp != null) { serviceREST.setResponseHTTPBody(responseHttp.getResponseHTTPBody()); serviceREST.setResponseHTTPCode(responseHttp.getResponseHTTPCode()); serviceREST.setResponseHTTPVersion(responseHttp.getResponseHTTPVersion()); serviceREST.setResponseHeaderList(responseHttp.getResponseHeaderList()); } break; case AppService.METHOD_HTTPPOST: LOG.info("Start preparing the REST Call (POST). " + servicePath); serviceREST.setServicePath(servicePath); HttpPost httpPost = new HttpPost(servicePath); // Timeout setup. httpPost.setConfig(requestConfig); // Content if (!(StringUtil.isNullOrEmpty(requestString))) { InputStream stream = new ByteArrayInputStream(requestString.getBytes(StandardCharsets.UTF_8)); InputStreamEntity reqEntity = new InputStreamEntity(stream); reqEntity.setChunked(true); httpPost.setEntity(reqEntity); serviceREST.setServiceRequest(requestString); } else { List<NameValuePair> nvps = new ArrayList<NameValuePair>(); for (AppServiceContent contentVal : contentList) { nvps.add(new BasicNameValuePair(contentVal.getKey(), contentVal.getValue())); } httpPost.setEntity(new UrlEncodedFormEntity(nvps)); serviceREST.setContentList(contentList); } // Header. for (AppServiceHeader contentHeader : headerList) { httpPost.addHeader(contentHeader.getKey(), contentHeader.getValue()); } serviceREST.setHeaderList(headerList); // Saving the service before the call Just in case it goes wrong (ex : timeout). result.setItem(serviceREST); LOG.info("Executing request " + httpPost.getRequestLine()); responseHttp = executeHTTPCall(httpclient, httpPost); if (responseHttp != null) { serviceREST.setResponseHTTPBody(responseHttp.getResponseHTTPBody()); serviceREST.setResponseHTTPCode(responseHttp.getResponseHTTPCode()); serviceREST.setResponseHTTPVersion(responseHttp.getResponseHTTPVersion()); serviceREST.setResponseHeaderList(responseHttp.getResponseHeaderList()); } else { message = new MessageEvent(MessageEventEnum.ACTION_FAILED_CALLSERVICE); message.setDescription(message.getDescription().replace("%SERVICE%", servicePath)); message.setDescription(message.getDescription().replace("%DESCRIPTION%", "Any issue was found when calling the service. Coud be a reached timeout during the call (." + timeOutMs + ")")); result.setResultMessage(message); return result; } break; } // Get result Content Type. if (responseHttp != null) { serviceREST.setResponseHTTPBodyContentType(AppServiceService.guessContentType(serviceREST, AppService.RESPONSEHTTPBODYCONTENTTYPE_JSON)); } result.setItem(serviceREST); message = new MessageEvent(MessageEventEnum.ACTION_SUCCESS_CALLSERVICE); message.setDescription(message.getDescription().replace("%SERVICEMETHOD%", method)); message.setDescription(message.getDescription().replace("%SERVICEPATH%", servicePath)); result.setResultMessage(message); } catch (SocketTimeoutException ex) { LOG.info("Exception when performing the REST Call. " + ex.toString()); message = new MessageEvent(MessageEventEnum.ACTION_FAILED_CALLSERVICE_TIMEOUT); message.setDescription(message.getDescription().replace("%SERVICEURL%", servicePath)); message.setDescription(message.getDescription().replace("%TIMEOUT%", String.valueOf(timeOutMs))); result.setResultMessage(message); return result; } catch (Exception ex) { LOG.error("Exception when performing the REST Call. " + ex.toString()); message = new MessageEvent(MessageEventEnum.ACTION_FAILED_CALLSERVICE); message.setDescription(message.getDescription().replace("%SERVICE%", servicePath)); message.setDescription( message.getDescription().replace("%DESCRIPTION%", "Error on CallREST : " + ex.toString())); result.setResultMessage(message); return result; } finally { try { httpclient.close(); } catch (IOException ex) { LOG.error(ex.toString()); } } return result; }
From source file:us.nineworlds.serenity.core.services.GDMService.java
@Override protected void onHandleIntent(Intent intent) { try {/*ww w.j a v a2s. c om*/ DatagramSocket socket = new DatagramSocket(32414); socket.setBroadcast(true); String data = "M-SEARCH * HTTP/1.1\r\n\r\n"; DatagramPacket packet = new DatagramPacket(data.getBytes(), data.length(), useMultiCastAddress(), 32414); // DatagramPacket packet = new DatagramPacket(data.getBytes(), // data.length(), getBroadcastAddress(), 32414); socket.send(packet); Log.d("GDMService", "Search Packet Broadcasted"); byte[] buf = new byte[256]; packet = new DatagramPacket(buf, buf.length); socket.setSoTimeout(2000); boolean listening = true; while (listening) { try { socket.receive(packet); String packetData = new String(packet.getData()); if (packetData.contains("HTTP/1.0 200 OK")) { Log.d("GDMService", "PMS Packet Received"); // Broadcast Received Packet Intent packetBroadcast = new Intent(GDMService.MSG_RECEIVED); packetBroadcast.putExtra("data", packetData); packetBroadcast.putExtra("ipaddress", packet.getAddress().toString()); LocalBroadcastManager.getInstance(this).sendBroadcast(packetBroadcast); } } catch (SocketTimeoutException e) { Log.d("GDMService", "Socket Timeout"); socket.close(); listening = false; Intent socketBroadcast = new Intent(GDMService.SOCKET_CLOSED); LocalBroadcastManager.getInstance(this).sendBroadcast(socketBroadcast); } } } catch (IOException e) { Log.e("GDMService", e.toString()); } }
From source file:com.frostwire.gui.updates.UpdateMessageReader.java
public void readUpdateFile() { HttpURLConnection connection = null; InputSource src = null;// w w w . ja va 2s. c o m try { String userAgent = "FrostWire/" + OSUtils.getOS() + "-" + OSUtils.getArchitecture() + "/" + FrostWireUtils.getFrostWireVersion(); connection = (HttpURLConnection) (new URL(getUpdateURL())).openConnection(); String url = getUpdateURL(); System.out.println("Reading update file from " + url); connection.setRequestProperty("User-Agent", userAgent); connection.setRequestProperty("Connection", "close"); connection.setReadTimeout(10000); // 10 secs timeout if (connection.getResponseCode() >= 400) { // invalid URL for sure connection.disconnect(); return; } src = new InputSource(connection.getInputStream()); XMLReader rdr = XMLReaderFactory .createXMLReader("com.sun.org.apache.xerces.internal.parsers.SAXParser"); rdr.setContentHandler(this); rdr.parse(src); connection.getInputStream().close(); connection.disconnect(); } catch (java.net.SocketTimeoutException e3) { System.out.println("UpdateMessageReadre.readUpdateFile() Socket Timeout Exeception " + e3.toString()); } catch (IOException e) { System.out.println("UpdateMessageReader.readUpdateFile() IO exception " + e.toString()); } catch (SAXException e2) { System.out.println("UpdateMessageReader.readUpdateFile() SAX exception " + e2.toString()); } }
From source file:com.juick.android.JASocketClient.java
public void readLoop() { long l = System.currentTimeMillis(); String cause = "??"; try {/*from w w w . jav a 2 s .c o m*/ int b; //StringBuilder buf = new StringBuilder(); ByteArrayOutputStream baos = new ByteArrayOutputStream(); final InputStream stream = is; if (stream != null) { while (true) { try { b = stream.read(); if (b == -1) { cause = "short read"; break; } } catch (SocketTimeoutException e) { if (listener != null) { if (!listener.onNoDataFromSocket()) { cause = "no pong reply withing interval"; break; } } continue; } if (shuttingDown) { cause = "shut down client"; break; } markActivity(); if (b == '\n') { if (listener != null) { listener.onWebSocketTextFrame(new String(baos.toByteArray(), "utf-8")); baos.reset(); } } else { baos.write(b); } } } } catch (Exception e) { cause = e.toString(); } finally { l = System.currentTimeMillis() - l; log("DISCONNECT readLoop: " + l + " msec worked, cause=" + cause); disconnect(); } }
From source file:winterwell.jtwitter.URLConnectionHttpClient.java
/** * Throw an exception if the connection failed * //from w ww . jav a2s .co m * @param connection */ final void processError(HttpURLConnection connection) { try { int code = connection.getResponseCode(); if (code == 200) return; URL url = connection.getURL(); // any explanation? String error = processError2_reason(connection); // which error? if (code == 401) { if (error.contains("Basic authentication is not supported")) throw new TwitterException.UpdateToOAuth(); throw new TwitterException.E401( error + "\n" + url + " (" + (name == null ? "anonymous" : name) + ")"); } if (code == 403) { // separate out the 403 cases processError2_403(url, error); } if (code == 404) { // user deleted? if (error != null && error.contains("deleted")) // Note: This is a 403 exception throw new TwitterException.SuspendedUser(error + "\n" + url); throw new TwitterException.E404(error + "\n" + url); } if (code == 406) // Hm: It might be nice to have info on post variables here throw new TwitterException.E406(error + "\n" + url); if (code == 413) throw new TwitterException.E413(error + "\n" + url); if (code == 416) throw new TwitterException.E416(error + "\n" + url); if (code == 420) throw new TwitterException.TooManyLogins(error + "\n" + url); if (code >= 500 && code < 600) throw new TwitterException.E50X(error + "\n" + url); // Over the rate limit? processError2_rateLimit(connection, code, error); // redirect?? if (code > 299 && code < 400) { String locn = connection.getHeaderField("Location"); throw new TwitterException(code + " " + error + " " + url + " -> " + locn); } // just report it as a vanilla exception throw new TwitterException(code + " " + error + " " + url); } catch (SocketTimeoutException e) { URL url = connection.getURL(); throw new TwitterException.Timeout(timeout + "milli-secs for " + url); } catch (ConnectException e) { // probably also a time out URL url = connection.getURL(); throw new TwitterException.Timeout(url.toString()); } catch (SocketException e) { // treat as a server error - because it probably is // (yes, it could also be an error at your end) throw new TwitterException.E50X(e.toString()); } catch (IOException e) { throw new TwitterException(e); } }
From source file:com.dimasdanz.kendalipintu.util.JSONParser.java
public JSONObject makeHttpRequest(String url, String method, List<NameValuePair> params) { try {//w w w .j av a2 s . c o m HttpParams httpParameters = new BasicHttpParams(); HttpConnectionParams.setSoTimeout(httpParameters, so_timeout); HttpConnectionParams.setConnectionTimeout(httpParameters, co_timeout); if (method == "POST") { DefaultHttpClient httpClient = new DefaultHttpClient(httpParameters); HttpPost httpPost = new HttpPost(url); httpPost.setEntity(new UrlEncodedFormEntity(params)); HttpResponse httpResponse = httpClient.execute(httpPost); HttpEntity httpEntity = httpResponse.getEntity(); is = httpEntity.getContent(); } else if (method == "GET") { DefaultHttpClient httpClient = new DefaultHttpClient(httpParameters); String paramString = URLEncodedUtils.format(params, "utf-8"); url += "?" + paramString; HttpGet httpGet = new HttpGet(url); HttpResponse httpResponse = httpClient.execute(httpGet); HttpEntity httpEntity = httpResponse.getEntity(); is = httpEntity.getContent(); } } catch (SocketTimeoutException e) { Log.e("SocketTimeoutException", "SocketTimeoutException"); e.printStackTrace(); return null; } catch (UnsupportedEncodingException e) { Log.e("UnsupportedEncodingException", "UnsupportedEncodingException"); e.printStackTrace(); return null; } catch (ClientProtocolException e) { Log.e("ClientProtocolException", "ClientProtocolException"); e.printStackTrace(); return null; } catch (IOException e) { Log.e("IOException", "IOException"); e.printStackTrace(); return null; } try { BufferedReader reader = new BufferedReader(new InputStreamReader(is, "iso-8859-1"), 8); StringBuilder sb = new StringBuilder(); String line = null; while ((line = reader.readLine()) != null) { sb.append(line + "\n"); } is.close(); json = sb.toString(); } catch (Exception e) { Log.e("Buffer Error", "Buffer Error : " + e.toString()); return null; } try { jObj = new JSONObject(json); } catch (JSONException e) { Log.e("JSON Parser", "Error parsing data " + e.toString()); return null; } return jObj; }