List of usage examples for java.net HttpURLConnection connect
public abstract void connect() throws IOException;
From source file:com.jeffrodriguez.webtools.client.URLConnectionWebClientImpl.java
@Override public byte[] get(String url, Map<String, List<String>> headers) throws IOException { logger.log(Level.INFO, "Getting byte[] from {0}", url); // Build and connect HttpURLConnection connection = buildConnection(url); applyHeaders(connection, headers);/*from www. j a va 2 s. co m*/ connection.connect(); // Check for errors checkForErrors(connection); // Get the result return disconnectAndReturn(connection, IOUtils.toByteArray(connection.getInputStream())); }
From source file:ch.lom.clemens.android.bibliography.data.JSONWebConnector.java
private String connect(String strURL) throws Exception { URL url = new URL(strURL); HttpURLConnection request = (HttpURLConnection) url.openConnection(); m_consumer.sign(request);//ww w. j av a 2 s . co m request.connect(); if (request.getResponseCode() == 200) { String strResponse = ""; InputStreamReader in = new InputStreamReader((InputStream) request.getContent()); BufferedReader buff = new BufferedReader(in); for (String strLine = ""; strLine != null; strLine = buff.readLine()) { strResponse += strLine + "\n"; } in.close(); return strResponse; } else { throw new Exception( "Mendeley Server returned " + request.getResponseCode() + ": " + request.getResponseMessage()); } }
From source file:edu.usf.cutr.opentripplanner.android.pois.Nominatim.java
public JSONArray requestPlaces(String paramName, String left, String top, String right, String bottom) { StringBuilder builder = new StringBuilder(); String encodedParamName;//from www . j ava2 s . c om String encodedParamLeft = ""; String encodedParamTop = ""; String encodedParamRight = ""; String encodedParamBottom = ""; try { encodedParamName = URLEncoder.encode(paramName, OTPApp.URL_ENCODING); if ((left != null) && (top != null) && (right != null) && (bottom != null)) { encodedParamLeft = URLEncoder.encode(left, OTPApp.URL_ENCODING); encodedParamTop = URLEncoder.encode(top, OTPApp.URL_ENCODING); encodedParamRight = URLEncoder.encode(right, OTPApp.URL_ENCODING); encodedParamBottom = URLEncoder.encode(bottom, OTPApp.URL_ENCODING); } } catch (UnsupportedEncodingException e1) { Log.e(OTPApp.TAG, "Error encoding Nominatim request"); e1.printStackTrace(); return null; } request += "&q=" + encodedParamName; if ((left != null) && (top != null) && (right != null) && (bottom != null)) { request += "&viewbox=" + encodedParamLeft + "," + encodedParamTop + "," + encodedParamRight + "," + encodedParamBottom; request += "&bounded=1"; } request += "&key=" + mApiKey; Log.d(OTPApp.TAG, request); HttpURLConnection urlConnection = null; try { URL url = new URL(request); urlConnection = (HttpURLConnection) url.openConnection(); urlConnection.setConnectTimeout(OTPApp.HTTP_CONNECTION_TIMEOUT); urlConnection.setReadTimeout(OTPApp.HTTP_SOCKET_TIMEOUT); urlConnection.connect(); int status = urlConnection.getResponseCode(); if (status == HttpURLConnection.HTTP_OK) { BufferedReader reader = new BufferedReader(new InputStreamReader(urlConnection.getInputStream())); String line; while ((line = reader.readLine()) != null) { builder.append(line); } } else { Log.e(OTPApp.TAG, "Error obtaining Nominatim response, status code: " + status); } } catch (IOException e) { e.printStackTrace(); Log.e(OTPApp.TAG, "Error obtaining Nominatim response" + e.toString()); return null; } finally { if (urlConnection != null) { urlConnection.disconnect(); } } Log.d(OTPApp.TAG, builder.toString()); JSONArray json = null; try { json = new JSONArray(builder.toString()); } catch (JSONException e) { Log.e(OTPApp.TAG, "Error parsing Nominatim data " + e.toString()); } return json; }
From source file:com.tcs.geofenceplugin.GeofenceTransitionsIntentService.java
@Override protected void onHandleIntent(Intent intent) { Log.d(TAG, "Handling intent"); gcmid = intent.getStringExtra("gcmid"); tokenid = intent.getStringExtra("tokenid"); GeofencingEvent geofencingEvent = GeofencingEvent.fromIntent(intent); if (geofencingEvent.hasError()) { String errorMessage = GeofenceErrorMessages.getErrorString(this, geofencingEvent.getErrorCode()); Log.d(TAG, errorMessage);/*w w w .j a v a 2s.c o m*/ return; } int geofenceTransition = geofencingEvent.getGeofenceTransition(); if (geofenceTransition == Geofence.GEOFENCE_TRANSITION_ENTER || geofenceTransition == Geofence.GEOFENCE_TRANSITION_EXIT) { Log.d(TAG, "recieved"); URL url; HttpURLConnection urlConnection = null; try { url = new URL("https://apphonics.tcs.com/geofence/Analytics?tokenid=" + tokenid); urlConnection = (HttpURLConnection) url.openConnection(); urlConnection.setRequestMethod("GET"); urlConnection.connect(); int responseCode = urlConnection.getResponseCode(); if (responseCode == 200) { Log.d(TAG, "Analytics data entered"); } } catch (Exception e) { e.printStackTrace(); } List<Geofence> triggeringGeofences = geofencingEvent.getTriggeringGeofences(); getGeofenceTransitionDetails(this, geofenceTransition, triggeringGeofences); } else { Log.e(TAG, getString(R.string.geofence_transition_invalid_type, geofenceTransition)); } }
From source file:com.baasbox.android.HttpUrlConnectionClient.java
@Override public HttpResponse execute(HttpRequest request) throws BaasException { try {/*from w ww . j a v a2 s . c o m*/ HttpURLConnection connection = openConnection(request.url); for (String name : request.headers.keySet()) { connection.addRequestProperty(name, request.headers.get(name)); } setupConnectionForRequest(connection, request); connection.connect(); int responseCode = -1; try { responseCode = connection.getResponseCode(); } catch (IOException e) { responseCode = connection.getResponseCode(); } Logger.info("Connection response received"); if (responseCode == -1) { throw new IOException("Connection failed"); } StatusLine line = new BasicStatusLine(new ProtocolVersion("HTTP", 1, 1), responseCode, connection.getResponseMessage()); BasicHttpResponse response = new BasicHttpResponse(line); response.setEntity(asEntity(connection)); for (Map.Entry<String, List<String>> header : connection.getHeaderFields().entrySet()) { if (header.getKey() != null) { Header h = new BasicHeader(header.getKey(), header.getValue().get(0)); response.addHeader(h); } } return response; } catch (IOException e) { throw new BaasIOException(e); } }
From source file:com.epam.catgenome.manager.externaldb.HttpDataManager.java
private String getResultFromURL(final String location) throws ExternalDbUnavailableException { HttpURLConnection conn = null; try {/*from w ww . j a v a2 s . c o m*/ conn = createConnection(location); HttpURLConnection.setFollowRedirects(true); conn.setDoInput(true); conn.setRequestProperty(CONTENT_TYPE, APPLICATION_JSON); conn.connect(); int status = conn.getResponseCode(); while (true) { long wait = 0; String header = conn.getHeaderField(HTTP_HEADER_RETRY_AFTER); if (header != null) { wait = Integer.valueOf(header); } if (wait == 0) { break; } LOGGER.info(String.format(WAITING_FORMAT, wait)); conn.disconnect(); Thread.sleep(wait * MILLIS_IN_SECOND); conn = (HttpURLConnection) new URL(location).openConnection(); conn.setDoInput(true); conn.connect(); status = conn.getResponseCode(); } return getHttpResult(status, location, conn); } catch (InterruptedException | IOException e) { throw new ExternalDbUnavailableException(String.format(EXCEPTION_MESSAGE, location), e); } finally { if (conn != null) { conn.disconnect(); } resetProxy(); } }
From source file:org.openmeetings.app.rss.LoadAtomRssFeed.java
public LinkedHashMap<String, LinkedHashMap<String, LinkedHashMap<String, Object>>> parseRssFeed( String urlEndPoint) {// ww w .j a v a 2s . com try { LinkedHashMap<String, LinkedHashMap<String, LinkedHashMap<String, Object>>> lMap = new LinkedHashMap<String, LinkedHashMap<String, LinkedHashMap<String, Object>>>(); URL url = new URL(urlEndPoint); HttpURLConnection conn = (HttpURLConnection) url.openConnection(); conn.setDoOutput(true); conn.setDoInput(true); conn.setRequestProperty("user-agent", "Mozilla/4.0 (compatible; MSIE 6.0; Windows NT 5.1; .NET CLR 1.1.4322)"); conn.setRequestProperty("Referer", "http://incubator.apache.org/openmeetings/"); conn.connect(); SAXReader reader = new SAXReader(); Document document = reader.read(conn.getInputStream()); Element root = document.getRootElement(); int l = 0; for (@SuppressWarnings("unchecked") Iterator<Element> i = root.elementIterator(); i.hasNext();) { Element item = i.next(); LinkedHashMap<String, LinkedHashMap<String, Object>> items = new LinkedHashMap<String, LinkedHashMap<String, Object>>(); boolean isSubElement = false; for (@SuppressWarnings("unchecked") Iterator<Element> it2 = item.elementIterator(); it2.hasNext();) { Element subItem = it2.next(); LinkedHashMap<String, Object> itemObj = new LinkedHashMap<String, Object>(); itemObj.put("name", subItem.getName()); itemObj.put("text", subItem.getText()); LinkedHashMap<String, String> attributes = new LinkedHashMap<String, String>(); for (@SuppressWarnings("unchecked") Iterator<Attribute> attr = subItem.attributeIterator(); attr.hasNext();) { Attribute at = attr.next(); attributes.put(at.getName(), at.getText()); } itemObj.put("attributes", attributes); // log.error(subItem.getName()+ ": " +subItem.getText()); items.put(subItem.getName(), itemObj); isSubElement = true; } if (isSubElement) { l++; lMap.put("item" + l, items); } } return lMap; } catch (Exception err) { log.error("[parseRssFeed]", err); } return null; }
From source file:com.atinternet.tracker.TVTrackingPlugin.java
@Override protected void execute(Tracker tracker) { this.tracker = tracker; try {/* www . j av a 2 s.c o m*/ if (sessionIsExpired()) { setDirectCampaignToRemanent(); URL url = new URL(tracker.TVTracking().getCampaignURL()); HttpURLConnection connection = (HttpURLConnection) url.openConnection(); connection.setReadTimeout(TIMEOUT); connection.setConnectTimeout(TIMEOUT); connection.setDoInput(true); connection.connect(); response = getTvTrackingResponse(stringifyTvTResponse(connection), connection); connection.disconnect(); } else { response = getTvTrackingResponse( Tracker.getPreferences().getString(TrackerConfigurationKeys.DIRECT_CAMPAIGN_SAVED, null), null); } Tool.executeCallback(tracker.getListener(), Tool.CallbackType.partner, "TV Tracking : " + response); Tracker.getPreferences().edit() .putLong(TrackerConfigurationKeys.LAST_TVT_EXECUTE_TIME, System.currentTimeMillis()).apply(); } catch (Exception e) { e.printStackTrace(); } }
From source file:com.trk.aboutme.facebook.android.Util.java
/** * Connect to an HTTP URL and return the response as a string. * * Note that the HTTP method override is used on non-GET requests. (i.e. * requests are made as "POST" with method specified in the body). * * @param url - the resource to open: must be a welformed URL * @param method - the HTTP method to use ("GET", "POST", etc.) * @param params - the query parameter for the URL (e.g. access_token=foo) * @return the URL contents as a String/*www. ja v a 2s. c o m*/ * @throws MalformedURLException - if the URL format is invalid * @throws IOException - if a network problem occurs */ @Deprecated public static String openUrl(String url, String method, Bundle params) throws MalformedURLException, IOException { // random string as boundary for multi-part http post String strBoundary = "3i2ndDfv2rTHiSisAbouNdArYfORhtTPEefj3q2f"; String endLine = "\r\n"; OutputStream os; if (method.equals("GET")) { url = url + "?" + encodeUrl(params); } Utility.logd("Facebook-Util", method + " URL: " + url); HttpURLConnection conn = (HttpURLConnection) new URL(url).openConnection(); conn.setRequestProperty("User-Agent", System.getProperties().getProperty("http.agent") + " FacebookAndroidSDK"); if (!method.equals("GET")) { Bundle dataparams = new Bundle(); for (String key : params.keySet()) { Object parameter = params.get(key); if (parameter instanceof byte[]) { dataparams.putByteArray(key, (byte[]) parameter); } } // use method override if (!params.containsKey("method")) { params.putString("method", method); } if (params.containsKey("access_token")) { String decoded_token = URLDecoder.decode(params.getString("access_token")); params.putString("access_token", decoded_token); } conn.setRequestMethod("POST"); conn.setRequestProperty("Content-Type", "multipart/form-data;boundary=" + strBoundary); conn.setDoOutput(true); conn.setDoInput(true); conn.setRequestProperty("Connection", "Keep-Alive"); conn.connect(); os = new BufferedOutputStream(conn.getOutputStream()); os.write(("--" + strBoundary + endLine).getBytes()); os.write((encodePostBody(params, strBoundary)).getBytes()); os.write((endLine + "--" + strBoundary + endLine).getBytes()); if (!dataparams.isEmpty()) { for (String key : dataparams.keySet()) { os.write(("Content-Disposition: form-data; filename=\"" + key + "\"" + endLine).getBytes()); os.write(("Content-Type: content/unknown" + endLine + endLine).getBytes()); os.write(dataparams.getByteArray(key)); os.write((endLine + "--" + strBoundary + endLine).getBytes()); } } os.flush(); } String response = ""; try { response = read(conn.getInputStream()); } catch (FileNotFoundException e) { // Error Stream contains JSON that we can parse to a FB error response = read(conn.getErrorStream()); } return response; }
From source file:edu.usf.cutr.opentripplanner.android.pois.GooglePlaces.java
public JSONObject requestPlaces(String paramLocation, String paramRadius, String paramName) { StringBuilder builder = new StringBuilder(); String encodedParamLocation = ""; String encodedParamRadius = ""; String encodedParamName;/*from w ww . j av a2s . co m*/ try { if ((paramLocation != null) && (paramRadius != null)) { encodedParamLocation = URLEncoder.encode(paramLocation, OTPApp.URL_ENCODING); encodedParamRadius = URLEncoder.encode(paramRadius, OTPApp.URL_ENCODING); } encodedParamName = URLEncoder.encode(paramName, OTPApp.URL_ENCODING); } catch (UnsupportedEncodingException e1) { Log.e(OTPApp.TAG, "Error encoding Google Places request"); e1.printStackTrace(); return null; } if ((paramLocation != null) && (paramRadius != null)) { request += "location=" + encodedParamLocation; request += "&radius=" + encodedParamRadius; request += "&query=" + encodedParamName; } else { request += "query=" + encodedParamName; } request += "&sensor=false"; request += "&key=" + getApiKey(); Log.d(OTPApp.TAG, request); HttpURLConnection urlConnection = null; try { URL url = new URL(request); urlConnection = (HttpURLConnection) url.openConnection(); urlConnection.setConnectTimeout(OTPApp.HTTP_CONNECTION_TIMEOUT); urlConnection.setReadTimeout(OTPApp.HTTP_SOCKET_TIMEOUT); urlConnection.connect(); int status = urlConnection.getResponseCode(); if (status == HttpURLConnection.HTTP_OK) { BufferedReader reader = new BufferedReader(new InputStreamReader(urlConnection.getInputStream())); String line; while ((line = reader.readLine()) != null) { builder.append(line); } } else { Log.e(OTPApp.TAG, "Error obtaining Google Places response, status code: \" + status"); } } catch (IOException e) { Log.e(OTPApp.TAG, "Error obtaining Google Places response" + e.toString()); e.printStackTrace(); return null; } finally { if (urlConnection != null) { urlConnection.disconnect(); } } Log.d(OTPApp.TAG, builder.toString()); JSONObject json = null; try { json = new JSONObject(builder.toString()); } catch (JSONException e) { Log.e(OTPApp.TAG, "Error parsing Google Places data " + e.toString()); } return json; }