List of usage examples for java.net HttpURLConnection disconnect
public abstract void disconnect();
From source file:de.mpg.escidoc.services.syndication.feed.Feed.java
/** * Search for the items for feed entries population. * The HTTP request to the SearchAndExport WEB interface is used * @param query is CQL query./*from w w w . jav a 2 s . com*/ * @param maximumRecords is the limit of the search * @param sortKeys * @return item list XML * @throws SyndicationException */ private String performSearch(String query, String maximumRecords, String sortKeys) throws SyndicationException { URL url; try { url = new URL(paramHash.get("${baseUrl}") + "/search/SearchAndExport?" + "cqlQuery=" + URLEncoder.encode(query, "UTF-8") + "&maximumRecords=" + URLEncoder.encode(maximumRecords, "UTF-8") + "&sortKeys=" + URLEncoder.encode(sortKeys, "UTF-8") + "&exportFormat=ESCIDOC_XML_V13" + "&sortOrder=descending" + "&language=all"); } catch (Exception e) { throw new SyndicationException("Wrong URL:", e); } Object content; URLConnection uconn; try { uconn = ProxyHelper.openConnection(url); if (!(uconn instanceof HttpURLConnection)) throw new IllegalArgumentException("URL protocol must be HTTP."); HttpURLConnection conn = (HttpURLConnection) uconn; InputStream stream = conn.getErrorStream(); if (stream != null) { conn.disconnect(); throw new SyndicationException(Utils.getInputStreamAsString(stream)); } else if ((content = conn.getContent()) != null && content instanceof InputStream) content = Utils.getInputStreamAsString((InputStream) content); else { conn.disconnect(); throw new SyndicationException("Cannot retrieve content from the HTTP response"); } conn.disconnect(); return (String) content; } catch (Exception e) { throw new SyndicationException(e); } }
From source file:com.projity.pm.graphic.frames.ApplicationStartupFactory.java
protected void getCredentials() { String authType = getOpt("credentials", 0); if (authType != null) { if ("login".equals(authType)) { login = getOpt("credentials", 1); password = getOpt("credentials", 2); } else if ("session".equals(authType)) { String partnerConnectionString = getOpt("credentials", 2); String timestamp = getOpt("timestamp"); long d = 0L; if (timestamp != null) { try { d = System.currentTimeMillis() - Long.parseLong(timestamp); } catch (NumberFormatException e) { }/*from w ww . j av a 2 s .co m*/ } String sessionId = getOpt("credentials", 1); //if (sessionId!=null&&d<=SESSION_EXPIRATION) if (sessionId != null || partnerConnectionString != null) try { Properties props = new Properties(); String urlString = serverUrl + "/" + Settings.WEB_APP + ((partnerConnectionString == null) ? "" : "/partner") + "/jnlp/projity_credentials.jnlp"; if (partnerConnectionString != null) urlString += "?" + partnerConnectionString; URL url = new URL(urlString); HttpURLConnection http = (HttpURLConnection) url.openConnection(); if (sessionId != null) http.setRequestProperty("Cookie", "JSESSIONID=" + sessionId); // if (partnerConnectionString == null) { // http.setRequestMethod("POST"); // } else { http.setRequestMethod("GET"); // } http.connect(); props.load(http.getInputStream()); http.disconnect(); //props.load((new URL(serverUrl+"/web/jnlp/projity_credentials.jnlp;jsessionid="+args[3])).openStream()); login = props.getProperty("login"); password = props.getProperty("password"); } catch (Exception e1) { e1.printStackTrace(); } } } }
From source file:de.akquinet.engineering.vaadinator.timesheet.service.AbstractCouchDbService.java
protected JSONObject getCouch(String urlPart) throws IOException, MalformedURLException, JSONException { HttpURLConnection couchConn = null; BufferedReader couchRead = null; try {/*from w w w. j a va 2s .c om*/ couchConn = (HttpURLConnection) (new URL(couchUrl + (couchUrl.endsWith("/") ? "" : "/") + urlPart)) .openConnection(); couchRead = new BufferedReader(new InputStreamReader(couchConn.getInputStream())); StringBuffer jsonBuf = new StringBuffer(); String line = couchRead.readLine(); while (line != null) { jsonBuf.append(line); line = couchRead.readLine(); } JSONObject couchObj = new JSONObject(jsonBuf.toString()); return couchObj; } finally { if (couchRead != null) { couchRead.close(); } if (couchConn != null) { couchConn.disconnect(); } } }
From source file:com.isdp.twitterposterandroid.GoogleManager.java
public String[] trySearch(String searchQuery, String searchEngineID) { try {/* w w w . j av a 2s . c o m*/ String query = URLEncoder.encode(searchQuery); URL url = new URL("https://www.googleapis.com/customsearch/v1?key=" + API_KEY + "&cx=" + searchEngineID + "&q=" + query); HttpURLConnection conn = (HttpURLConnection) url.openConnection(); conn.setRequestMethod("GET"); conn.setRequestProperty("Accept", "application/json"); InputStream inputStream = conn.getInputStream(); String jsonStr = null; if (inputStream != null) jsonStr = Util.convertInputStreamToString(inputStream); JSONObject jsonObj = new JSONObject( jsonStr.substring(jsonStr.indexOf("{"), jsonStr.lastIndexOf("}") + 1)); String[] results = null; if (searchEngineID.equals(SEARCH_WIKI)) results = parseWiki(jsonObj); else if (searchEngineID.equals(SEARCH_YELP)) results = parseYelp(jsonObj); conn.disconnect(); return results; } catch (Exception e) { e.printStackTrace(); return null; } }
From source file:com.orange.oidc.tim.service.HttpOpenidConnect.java
static String getUserInfo(String server_url, String access_token) { // android.os.Debug.waitForDebugger(); // check if server is valid if (isEmpty(server_url) || isEmpty(access_token)) { return null; }//w w w .j av a 2 s.c o m String userinfo_endpoint = getEndpointFromConfigOidc("userinfo_endpoint", server_url); if (isEmpty(userinfo_endpoint)) { Logd(TAG, "getUserInfo : could not get endpoint on server : " + server_url); return null; } Logd(TAG, "getUserInfo : " + userinfo_endpoint); // build connection HttpURLConnection huc = getHUC(userinfo_endpoint); huc.setInstanceFollowRedirects(false); // huc.setRequestProperty("Content-Type","application/x-www-form-urlencoded"); huc.setRequestProperty("Authorization", "Bearer " + access_token); // default result String result = null; try { // try to establish connection huc.connect(); // get result int responseCode = huc.getResponseCode(); Logd(TAG, "getUserInfo 2 response: " + responseCode); // if 200, read http body if (responseCode == 200) { InputStream is = huc.getInputStream(); result = convertStreamToString(is); is.close(); } // close connection huc.disconnect(); } catch (Exception e) { Logd(TAG, "getUserInfo failed"); e.printStackTrace(); } return result; }
From source file:com.zhonghui.tool.controller.HttpClient.java
/** * Response?/*from ww w .ja v a2 s . c o m*/ * * @param connection * @param encoding ? * @return * @throws URISyntaxException * @throws IOException */ private InputStream responseInput(final HttpURLConnection connection, String encoding) throws URISyntaxException, IOException, Exception { InputStream in = null; try { if (200 == connection.getResponseCode()) { in = connection.getInputStream(); } else { in = connection.getErrorStream(); } logger.info("HTTP Return Status-Code:[" + connection.getResponseCode() + "]"); return in; } catch (Exception e) { throw e; } finally { if (null != connection) { connection.disconnect(); } } }
From source file:co.cask.cdap.gateway.router.NettyRouterTestBase.java
@Test public void testConnectionIdleTimeoutWithMultipleServers() throws Exception { defaultServer2.cancelRegistration(); URL url = new URL(resolveURI(Constants.Router.GATEWAY_DISCOVERY_NAME, "/v2/ping")); HttpURLConnection urlConnection = openURL(url); Assert.assertEquals(200, urlConnection.getResponseCode()); urlConnection.getInputStream().close(); urlConnection.disconnect(); // requests past this point will go to defaultServer2 defaultServer1.cancelRegistration(); defaultServer2.registerServer();// w ww . java 2 s . c o m for (int i = 0; i < 4; i++) { // this is an assumption that CONNECTION_IDLE_TIMEOUT_SECS is more than 1 second TimeUnit.SECONDS.sleep(1); url = new URL(resolveURI(Constants.Router.GATEWAY_DISCOVERY_NAME, "/v1/ping/" + i)); urlConnection = openURL(url); Assert.assertEquals(200, urlConnection.getResponseCode()); urlConnection.getInputStream().close(); urlConnection.disconnect(); } // for the past 4 seconds, we've been making requests to defaultServer2; therefore, defaultServer1 will have closed // its single connection Assert.assertEquals(1, defaultServer1.getNumConnectionsOpened()); Assert.assertEquals(1, defaultServer1.getNumConnectionsClosed()); // however, the connection to defaultServer2 is not timed out, because we've been making requests to it Assert.assertEquals(1, defaultServer2.getNumConnectionsOpened()); Assert.assertEquals(0, defaultServer2.getNumConnectionsClosed()); defaultServer2.registerServer(); defaultServer1.cancelRegistration(); url = new URL(resolveURI(Constants.Router.GATEWAY_DISCOVERY_NAME, "/v2/ping")); urlConnection = openURL(url); Assert.assertEquals(200, urlConnection.getResponseCode()); urlConnection.getInputStream().close(); urlConnection.disconnect(); }
From source file:com.google.gdocsfs.GoogleDocs.java
public final int getContentLength(URL source) throws IOException { HttpURLConnection connection = null; try {/* w ww. jav a 2 s . c o m*/ connection = getConnection(source, "HEAD"); connection.connect(); { // get content length int contentLength = -1; String contentLengthStr = connection.getHeaderField("Content-Length"); if (contentLengthStr != null) { try { contentLength = Integer.parseInt(contentLengthStr); } catch (NumberFormatException e) { log.warn("Can't parse the content lenght.", e); } } return contentLength; } } finally { if (connection != null) { connection.disconnect(); } } }
From source file:com.gottibujiku.httpjsonexchange.main.HttpJSONExchange.java
/** * This method sends a GET request to the server. * It prepares the request by creating a valid URL with a query string(if any) * then adds the headers and then open a connection to the server; retrieves * response and return result as a JSON Object * /*from ww w . j a v a 2 s . c o m*/ * @return a JSON object containing the response */ public JSONObject sendGETRequest() { /* 1. Form the query string by concatenating param names and their values * 2. Add HTTP headers to the request and set request method to GET * 3. Open stream and read server response * */ if (fullDomainName == null) { throw new NullPointerException("No URL provided! Please provide one!");//No domain name was provided } JSONObject jsonResponse = null; URL url = null;//a url object to hold a complete URL try { url = new URL(fullDomainName + QUERY_SEPARATOR + getFormatedQueryString(queryParams));//a complete URL HttpURLConnection connection = (HttpURLConnection) url.openConnection(); connection = addHeadersToRequest(headers, connection);//add headers to connection and get modified instance connection.setRequestProperty("Accept-Charset", UTF_CHARSET);//accept the given encoding //a call to connection.connect() is superfluous since connect will be called //implicitly when the stream is opened connection.setRequestMethod("GET"); String jsonString = getServerResponse(connection); connection.disconnect(); jsonResponse = new JSONObject(jsonString);//change the response into a json object } catch (MalformedURLException e) { e.printStackTrace(); return null;//return if the URL is malformed } catch (IOException e) { e.printStackTrace(); return null;//if failed to open a connection } catch (JSONException e) { e.printStackTrace(); return null;//invalid JSON response } return jsonResponse; }
From source file:com.gottibujiku.httpjsonexchange.main.HttpJSONExchange.java
/** * This method sends a GET request to the server. * It prepares the request by creating a valid URL with a query string(if any) * then adds the headers and then open a connection to the server; retrieves * response and return result as a JSON Object * //from ww w .ja v a 2 s. c o m * * @param fullDomainName a fully qualified domain name including the protocol * @param queryParams parameters to be sent in the query string * @param headers additional headers * @return a JSON object containing the response */ public JSONObject sendGETRequest(String fullDomainName, HashMap<String, String> queryParams, HashMap<String, String> headers) { /* 1. Form the query string by concatenating param names and their values * 2. Add HTTP headers to the request and set request method to GET * 3. Open stream and read server response * */ if (fullDomainName == null) { throw new NullPointerException("No URL provided! Please provide one!");//No domain name was provided } JSONObject jsonResponse = null; URL url = null;//a url object to hold a complete URL try { url = new URL(fullDomainName + QUERY_SEPARATOR + getFormatedQueryString(queryParams));//a complete URL HttpURLConnection connection = (HttpURLConnection) url.openConnection(); connection = addHeadersToRequest(headers, connection);//add headers to connection and get modified instance connection.setRequestProperty("Accept-Charset", UTF_CHARSET);//accept the given encoding //a call to connection.connect() is superfluous since connect will be called //implicitly when the stream is opened connection.setRequestMethod("GET"); String jsonString = getServerResponse(connection); connection.disconnect(); jsonResponse = new JSONObject(jsonString);//change the response into a json object } catch (MalformedURLException e) { e.printStackTrace(); return null;//return if the URL is malformed } catch (IOException e) { e.printStackTrace(); return null;//if failed to open a connection } catch (JSONException e) { e.printStackTrace(); return null;//invalid JSON response } return jsonResponse; }