public void setAndAccessURL(String urlString) { Log.i("tag", "akses mulai"); // while(isConnecting){ try { if (Thread.interrupted()) listener.onCancelledConnection(); int response = -1; URL url = new URL(urlString); conn = url.openConnection(); if (!(conn instanceof HttpURLConnection)) throw new IOException("Not an HTTP connection"); HttpURLConnection httpConn = (HttpURLConnection) conn; httpConn.setAllowUserInteraction(false); httpConn.setInstanceFollowRedirects(true); httpConn.setRequestMethod("GET"); httpConn.setConnectTimeout(60000); httpConn.connect(); int length = httpConn.getContentLength(); response = httpConn.getResponseCode(); if (response == HttpURLConnection.HTTP_OK) { is = httpConn.getInputStream(); if (listener != null) { Log.i("tag", "sukses"); listener.onReceivedResponse(is, length); } } else { Log.e("tag", "not ok"); listener.onConnectionResponseNotOk(); } httpConn.disconnect(); if (is != null) { is.close(); is = null; } } catch (SocketTimeoutException ex) { if (listener != null) { Log.e("error", "connection timeout"); listener.onConnectionTimeout(); } } catch (InterruptedIOException ex) { if (listener != null) { listener.onCancelledConnection(); } } catch (Exception ex) { if (listener != null) { Log.e("error", "error connecting to the internet"); listener.onConnectionError(ex); } } // } }
public void cancel(Thread name) { System.out.println("canceling connection"); name.interrupt(); try { if (is != null) { is.close(); is = null; } if (httpConn != null) { httpConn.disconnect(); httpConn = null; } if (conn != null) { conn = null; } listener.onCancelledConnection(); } catch (Exception e) { listener.onConnectionError(e); } }