List of usage examples for java.net HttpURLConnection disconnect
public abstract void disconnect();
From source file:edu.umn.cs.spatialHadoop.nasa.HTTPInputStream.java
private long getContentLength() throws IOException { if (length < 0) { int retries = Math.max(1, HTTPFileSystem.retries); HttpURLConnection localConn = null; while (localConn == null && retries-- > 0) { try { localConn = (HttpURLConnection) url.openConnection(); } catch (java.net.SocketException e) { if (retries == 0) throw e; LOG.info("Error accessing file '" + url + "'. Trials left: " + retries); } catch (java.net.UnknownHostException e) { if (retries == 0) throw e; LOG.info("Error accessing file '" + url + "'. Trials left: " + retries); }/* www . j a va2 s.c om*/ } length = localConn.getContentLength(); localConn.disconnect(); } return length; }
From source file:eu.creatingfuture.propeller.webLoader.servlets.WebRequestServlet.java
@Override protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException { resp.addHeader("Access-Control-Allow-Origin", "*"); String getUrl = req.getParameter("get"); if (getUrl == null) { resp.sendError(400);//from w ww . j av a 2 s . c o m return; } logger.info(getUrl); URL url; HttpURLConnection connection = null; try { url = new URL(getUrl); connection = (HttpURLConnection) url.openConnection(); connection.setRequestMethod("GET"); connection.setUseCaches(false); resp.setContentType(connection.getContentType()); resp.setContentLengthLong(connection.getContentLengthLong()); logger.log(Level.INFO, "Content length: {0} response code: {1} content type: {2}", new Object[] { connection.getContentLengthLong(), connection.getResponseCode(), connection.getContentType() }); resp.setStatus(connection.getResponseCode()); IOUtils.copy(connection.getInputStream(), resp.getOutputStream()); } catch (IOException ioe) { resp.sendError(500, ioe.getMessage()); } finally { if (connection != null) { connection.disconnect(); } } }
From source file:com.kinvey.business_logic.collection_access.MongoRequest.java
private HttpResponse makeRequest() throws CollectionAccessException { KinveyAuthCredentials authCredentials = KinveyAuthCredentials.getInstance(); try {// ww w . j a v a 2 s . co m String encodedUrl = this.protocol + "://" + this.baseUrl + "/" + authCredentials.getAppId() + "/" + this.collection.collectionName + "/" + this.collectionOperation.getEndPoint(); String userPass = authCredentials.getAppId() + ":" + authCredentials.getMasterSecret(); String authString = "Basic " + new String(Base64.encode(userPass), "UTF-8"); URL url = new URL(encodedUrl); HttpURLConnection conn = (HttpURLConnection) url.openConnection(); conn.setDoOutput(true); conn.setRequestMethod("POST"); conn.setRequestProperty("Content-Type", "application/json"); conn.setRequestProperty("Authorization", authString); String input = buildBody(); OutputStream os = conn.getOutputStream(); os.write(input.getBytes()); os.flush(); BufferedReader br = new BufferedReader(new InputStreamReader((conn.getInputStream()))); String tmpOutput; String contentBody = ""; while ((tmpOutput = br.readLine()) != null) { contentBody += tmpOutput; } conn.disconnect(); HttpResponse response = new HttpResponse(contentBody); return response; } catch (IOException e) { throw new CollectionAccessException(e); } }
From source file:eu.geopaparazzi.library.network.NetworkUtilities.java
/** * Sends a string via POST to a given url. * // w w w .ja v a 2 s . com * @param urlStr the url to which to send to. * @param string the string to send as post body. * @param user the user or <code>null</code>. * @param password the password or <code>null</code>. * @return the response. * @throws Exception */ public static String sendPost(String urlStr, String string, String user, String password) throws Exception { BufferedOutputStream wr = null; HttpURLConnection conn = null; try { conn = makeNewConnection(urlStr); conn.setRequestMethod("POST"); conn.setDoOutput(true); conn.setDoInput(true); // conn.setChunkedStreamingMode(0); conn.setUseCaches(false); if (user != null && password != null) { conn.setRequestProperty("Authorization", getB64Auth(user, password)); } conn.connect(); // Make server believe we are form data... wr = new BufferedOutputStream(conn.getOutputStream()); byte[] bytes = string.getBytes(); wr.write(bytes); wr.flush(); int responseCode = conn.getResponseCode(); StringBuilder returnMessageBuilder = new StringBuilder(); if (responseCode == HttpURLConnection.HTTP_OK) { BufferedReader br = new BufferedReader(new InputStreamReader(conn.getInputStream(), "utf-8")); while (true) { String line = br.readLine(); if (line == null) break; returnMessageBuilder.append(line + "\n"); } br.close(); } return returnMessageBuilder.toString(); } catch (Exception e) { e.printStackTrace(); throw e; } finally { if (conn != null) conn.disconnect(); } }
From source file:org.runnerup.export.EndomondoSynchronizer.java
@Override public Status getFeed(FeedUpdater feedUpdater) { Status s;//from ww w. ja v a2 s.com if ((s = connect()) != Status.OK) { return s; } StringBuilder url = new StringBuilder(); url.append(FEED_URL).append("?authToken=").append(authToken); url.append("&maxResults=25"); HttpURLConnection conn = null; Exception ex = null; try { conn = (HttpURLConnection) new URL(url.toString()).openConnection(); conn.setRequestMethod(RequestMethod.GET.name()); final InputStream in = new BufferedInputStream(conn.getInputStream()); final JSONObject reply = SyncHelper.parse(in); int responseCode = conn.getResponseCode(); String amsg = conn.getResponseMessage(); conn.disconnect(); if (responseCode == HttpStatus.SC_OK) { parseFeed(feedUpdater, reply); return Status.OK; } ex = new Exception(amsg); } catch (IOException e) { ex = e; } catch (JSONException e) { ex = e; } s = Synchronizer.Status.ERROR; s.ex = ex; if (ex != null) { ex.printStackTrace(); } return s; }
From source file:eu.semlibproject.annotationserver.restapis.ServicesAPI.java
/** * Implement a simple proxy//from w w w. ja v a2 s. c o m * * @param requestedURL the requested URL * @param req the HttpServletRequest * @return */ @GET @Path("proxy") public Response proxy(@QueryParam(SemlibConstants.URL_PARAM) String requestedURL, @Context HttpServletRequest req) { BufferedReader in = null; try { URL url = new URL(requestedURL); URLConnection urlConnection = url.openConnection(); int proxyConnectionTimeout = ConfigManager.getInstance().getProxyAPITimeout(); // Set base properties urlConnection.setUseCaches(false); urlConnection.setConnectTimeout(proxyConnectionTimeout * 1000); // set max response timeout 15 sec String acceptedDataFormat = req.getHeader(SemlibConstants.HTTP_HEADER_ACCEPT); if (StringUtils.isNotBlank(acceptedDataFormat)) { urlConnection.addRequestProperty(SemlibConstants.HTTP_HEADER_ACCEPT, acceptedDataFormat); } // Open the connection urlConnection.connect(); if (urlConnection instanceof HttpURLConnection) { HttpURLConnection httpConnection = (HttpURLConnection) urlConnection; int statusCode = httpConnection.getResponseCode(); if (statusCode == HttpURLConnection.HTTP_MOVED_TEMP || statusCode == HttpURLConnection.HTTP_MOVED_PERM) { // Follow the redirect String newLocation = httpConnection.getHeaderField(SemlibConstants.HTTP_HEADER_LOCATION); httpConnection.disconnect(); if (StringUtils.isNotBlank(newLocation)) { return this.proxy(newLocation, req); } else { return Response.status(statusCode).build(); } } else if (statusCode == HttpURLConnection.HTTP_OK) { // Send the response StringBuilder sbf = new StringBuilder(); // Check if the contentType is supported boolean contentTypeSupported = false; String contentType = httpConnection.getHeaderField(SemlibConstants.HTTP_HEADER_CONTENT_TYPE); List<String> supportedMimeTypes = ConfigManager.getInstance().getProxySupportedMimeTypes(); if (contentType != null) { for (String cMime : supportedMimeTypes) { if (contentType.equals(cMime) || contentType.contains(cMime)) { contentTypeSupported = true; break; } } } if (!contentTypeSupported) { httpConnection.disconnect(); return Response.status(Status.NOT_ACCEPTABLE).build(); } String contentEncoding = httpConnection.getContentEncoding(); if (StringUtils.isBlank(contentEncoding)) { contentEncoding = "UTF-8"; } InputStreamReader inStrem = new InputStreamReader((InputStream) httpConnection.getContent(), Charset.forName(contentEncoding)); in = new BufferedReader(inStrem); String inputLine; while ((inputLine = in.readLine()) != null) { sbf.append(inputLine); sbf.append("\r\n"); } in.close(); httpConnection.disconnect(); return Response.status(statusCode).header(SemlibConstants.HTTP_HEADER_CONTENT_TYPE, contentType) .entity(sbf.toString()).build(); } else { httpConnection.disconnect(); return Response.status(statusCode).build(); } } return Response.status(Status.BAD_REQUEST).build(); } catch (MalformedURLException ex) { logger.log(Level.SEVERE, null, ex); return Response.status(Status.BAD_REQUEST).build(); } catch (IOException ex) { logger.log(Level.SEVERE, null, ex); return Response.status(Status.INTERNAL_SERVER_ERROR).build(); } finally { if (in != null) { try { in.close(); } catch (IOException ex) { logger.log(Level.SEVERE, null, ex); return Response.status(Status.INTERNAL_SERVER_ERROR).build(); } } } }
From source file:export.NikePlus.java
JSONObject makeGetRequest(String url) throws MalformedURLException, IOException, JSONException { HttpURLConnection conn = null; try {/*from ww w . j av a2s . c om*/ conn = (HttpURLConnection) new URL(url).openConnection(); conn.setRequestMethod("GET"); conn.addRequestProperty("Accept", "application/json"); conn.addRequestProperty("User-Agent", USER_AGENT); conn.addRequestProperty("appid", APP_ID); final InputStream in = new BufferedInputStream(conn.getInputStream()); final JSONObject reply = parse(in); final int code = conn.getResponseCode(); conn.disconnect(); if (code == 200) return reply; } finally { if (conn != null) conn.disconnect(); } return new JSONObject(); }
From source file:com.meetingninja.csse.database.ContactDatabaseAdapter.java
public static List<Contact> addContact(String contactUserID) throws IOException { String _url = getBaseUri().build().toString(); URL url = new URL(_url); HttpURLConnection conn = (HttpURLConnection) url.openConnection(); conn.setRequestMethod(IRequest.PUT); addRequestHeader(conn, false);//from w w w. ja v a2 s.c o m SessionManager session = SessionManager.getInstance(); String userID = session.getUserID(); ByteArrayOutputStream json = new ByteArrayOutputStream(); // this type of print stream allows us to get a string easily PrintStream ps = new PrintStream(json); // Create a generator to build the JSON string JsonGenerator jgen = JFACTORY.createGenerator(ps, JsonEncoding.UTF8); // Build JSON Object for Title jgen.writeStartObject(); jgen.writeStringField(Keys.User.ID, userID); jgen.writeArrayFieldStart(Keys.User.CONTACTS); jgen.writeStartObject(); jgen.writeStringField(Keys.User.CONTACTID, contactUserID); jgen.writeEndObject(); jgen.writeEndArray(); jgen.writeEndObject(); jgen.close(); String payload = json.toString("UTF8"); ps.close(); sendPostPayload(conn, payload); String response = getServerResponse(conn); // TODO: put add useful check here // User userContact=null; // String relationID=null; // String result = new String(); // if (!response.isEmpty()) { // JsonNode contactNode = MAPPER.readTree(response); // if (!contactNode.has(Keys.User.ID)) { // result = "invalid"; // } else { // result = contactNode.get(Keys.User.ID).asText(); // userContact = getUserInfo(result); // relationID = contactNode.get(Keys.User.RELATIONID).asText(); // } // } // if (!result.equalsIgnoreCase("invalid")) // g.setID(result); conn.disconnect(); // Contact contact = new Contact(userContact,relationID); List<Contact> contacts = new ArrayList<Contact>(); contacts = getContacts(userID); return contacts; }
From source file:com.github.hipchat.api.HipChat.java
public Room getRoom(String roomId) { String query = String.format(HipChatConstants.ROOMS_SHOW_QUERY_FORMAT, roomId, HipChatConstants.JSON_FORMAT, authToken);//from ww w . j av a 2s . c o m InputStream input = null; Room result = null; HttpURLConnection connection = null; try { URL requestUrl = getRequestUrl(HipChatConstants.API_BASE, HipChatConstants.ROOMS_SHOW, query); connection = getGetConnection(requestUrl); input = connection.getInputStream(); result = RoomParser.parseRoom(this, input); } catch (IOException e) { LogMF.error(logger, "IO Exception: {0}", new Object[] { e.getMessage() }); } finally { IOUtils.closeQuietly(input); connection.disconnect(); } return result; }