List of usage examples for java.net HttpURLConnection connect
public abstract void connect() throws IOException;
From source file:com.intellij.lang.jsgraphql.languageservice.JSGraphQLNodeLanguageServiceClient.java
private static <R> R executeRequest(Request request, Class<R> responseClass, @NotNull Project project, boolean setProjectDir) { URL url = getJSGraphQLNodeLanguageServiceInstance(project, setProjectDir); if (url == null) { return null; }/*from ww w .j a v a2 s . co m*/ HttpURLConnection httpConnection = null; try { httpConnection = (HttpURLConnection) url.openConnection(); httpConnection.setConnectTimeout(50); httpConnection.setReadTimeout(1000); httpConnection.setRequestMethod("POST"); httpConnection.setDoOutput(true); httpConnection.setRequestProperty("Content-Type", "application/json"); httpConnection.connect(); try (OutputStreamWriter writer = new OutputStreamWriter(httpConnection.getOutputStream())) { final String jsonRequest = new Gson().toJson(request); writer.write(jsonRequest); writer.flush(); writer.close(); } if (httpConnection.getResponseCode() == 200) { if (responseClass == null) { return null; } try (InputStream inputStream = httpConnection.getInputStream()) { String jsonResponse = IOUtils.toString(inputStream, "UTF-8"); R response = new Gson().fromJson(jsonResponse, responseClass); return response; } } else { log.warn("Got error from JS GraphQL Language Service: HTTP " + httpConnection.getResponseCode() + ": " + httpConnection.getResponseMessage()); } } catch (IOException e) { log.warn("Unable to connect to dev server", e); } finally { if (httpConnection != null) { httpConnection.disconnect(); } } return null; }
From source file:Main.java
/** * On some devices we have to hack:// w w w .j a v a 2 s .c o m * http://developers.sun.com/mobility/reference/techart/design_guidelines/http_redirection.html * @return the resolved url if any. Or null if it couldn't resolve the url * (within the specified time) or the same url if response code is OK */ public static String getResolvedUrl(String urlAsString, int timeout) { try { URL url = new URL(urlAsString); //using proxy may increase latency HttpURLConnection hConn = (HttpURLConnection) url.openConnection(Proxy.NO_PROXY); // force no follow hConn.setInstanceFollowRedirects(false); // the program doesn't care what the content actually is !! // http://java.sun.com/developer/JDCTechTips/2003/tt0422.html hConn.setRequestMethod("HEAD"); // default is 0 => infinity waiting hConn.setConnectTimeout(timeout); hConn.setReadTimeout(timeout); hConn.connect(); int responseCode = hConn.getResponseCode(); hConn.getInputStream().close(); if (responseCode == HttpURLConnection.HTTP_OK) return urlAsString; String loc = hConn.getHeaderField("Location"); if (responseCode == HttpURLConnection.HTTP_MOVED_PERM && loc != null) return loc.replaceAll(" ", "+"); } catch (Exception ex) { } return ""; }
From source file:com.evrythng.java.wrapper.util.FileUtils.java
private static HttpURLConnection getConnectionForPrivateUpload(final URL url, final String contentType) throws IOException { HttpURLConnection connection = (HttpURLConnection) url.openConnection(); connection.setRequestMethod(HttpPut.METHOD_NAME); connection.setRequestProperty(HttpHeaders.CONTENT_TYPE, contentType); connection.setRequestProperty(X_AMZ_ACL_HEADER_NAME, X_AMZ_ACL_HEADER_VALUE_PRIVATE); connection.setDoOutput(true);/*from w w w .ja v a 2 s .co m*/ connection.connect(); return connection; }
From source file:a122016.rr.com.alertme.QueryUtils.java
/** * Make an HTTP request to the given URL and return a String as the response. *//*from w w w.j ava2 s . c o m*/ private static String makeHttpRequest(URL url) throws IOException { String jsonResponse = ""; // If the URL is null, then return early. if (url == null) { return jsonResponse; } HttpURLConnection urlConnection = null; InputStream inputStream = null; try { urlConnection = (HttpURLConnection) url.openConnection(); urlConnection.setReadTimeout(10000 /* milliseconds */); urlConnection.setConnectTimeout(15000 /* milliseconds */); urlConnection.setRequestMethod("GET"); urlConnection.connect(); // If the request was successful (response code 200), // then read the input stream and parse the response. if (urlConnection.getResponseCode() == 200) { inputStream = urlConnection.getInputStream(); jsonResponse = readFromStream(inputStream); } else { Log.e(LOG_TAG, "Error response code: " + urlConnection.getResponseCode()); } } catch (IOException e) { Log.e(LOG_TAG, "Problem retrieving the Places JSON results.", e); } finally { if (urlConnection != null) { urlConnection.disconnect(); } if (inputStream != null) { // Closing the input stream could throw an IOException, which is why // the makeHttpRequest(URL url) method signature specifies than an IOException // could be thrown. inputStream.close(); } } return jsonResponse; }
From source file:com.evrythng.java.wrapper.util.FileUtils.java
private static HttpURLConnection getConnectionForPublicUpload(final URL url, final String contentType) throws IOException { HttpURLConnection connection = (HttpURLConnection) url.openConnection(); connection.setRequestMethod(HttpPut.METHOD_NAME); connection.setRequestProperty(HttpHeaders.CONTENT_TYPE, contentType); connection.setRequestProperty(X_AMZ_ACL_HEADER_NAME, X_AMZ_ACL_HEADER_VALUE_PUBLIC_READ); connection.setDoOutput(true);/*from w w w .ja v a2s .com*/ connection.connect(); return connection; }
From source file:ee.ria.xroad.signer.certmanager.OcspClient.java
private static HttpURLConnection createConnection(URL url) throws IOException { HttpURLConnection connection = (HttpURLConnection) url.openConnection(); connection.setRequestProperty(MimeUtils.HEADER_CONTENT_TYPE, MimeTypes.OCSP_REQUEST); connection.setRequestProperty("Accept", MimeTypes.OCSP_RESPONSE); connection.setDoOutput(true);//from w w w . j av a 2 s . c o m connection.setConnectTimeout(CONNECT_TIMEOUT_MS); connection.setReadTimeout(READ_TIMEOUT_MS); connection.connect(); return connection; }
From source file:net.kourlas.voipms_sms.Utils.java
/** * Retrieves a JSON object from the specified URL. * <p/>/*from www . j ava2 s .c om*/ * Note that this is a blocking method; it should not be called from the URI thread. * * @param urlString The URL to retrieve the JSON from. * @return The JSON object at the specified URL. * @throws IOException if a connection to the server could not be established. * @throws JSONException if the server did not return valid JSON. */ public static JSONObject getJson(String urlString) throws IOException, JSONException { URL url = new URL(urlString); HttpURLConnection connection = (HttpURLConnection) url.openConnection(); connection.setReadTimeout(10000); connection.setConnectTimeout(15000); connection.setRequestMethod("GET"); connection.setDoInput(true); connection.connect(); BufferedReader reader = new BufferedReader(new InputStreamReader(connection.getInputStream(), "UTF-8")); StringBuilder data = new StringBuilder(); String newLine = System.getProperty("line.separator"); String line; while ((line = reader.readLine()) != null) { data.append(line); data.append(newLine); } reader.close(); return new JSONObject(data.toString()); }
From source file:com.raphfrk.craftproxyclient.net.auth.AuthManager.java
@SuppressWarnings("unchecked") public static void authServer16(String hash) throws IOException { URL url;// ww w . java 2 s. c o m String username; String accessToken; try { if (loginDetails == null) { throw new IOException("Not logged in"); } try { username = URLEncoder.encode(getUsername(), "UTF-8"); accessToken = URLEncoder.encode(getAccessToken(), "UTF-8"); hash = URLEncoder.encode(hash, "UTF-8"); } catch (UnsupportedEncodingException e) { throw new IOException("Username/password encoding error", e); } String urlString; urlString = sessionServer16 + "user=" + username + "&sessionId=" + accessToken + "&serverId=" + hash; url = new URL(urlString); } catch (MalformedURLException e) { throw new IOException("Auth server URL error", e); } HttpURLConnection con = (HttpURLConnection) url.openConnection(); con.setInstanceFollowRedirects(false); con.setReadTimeout(5000); con.setConnectTimeout(5000); con.connect(); if (con.getResponseCode() != 200) { throw new IOException("Auth server rejected username and password"); } BufferedReader reader = new BufferedReader( new InputStreamReader(con.getInputStream(), StandardCharsets.UTF_8)); try { String reply = reader.readLine(); if (!"OK".equals(reply)) { throw new IOException("Auth server replied (" + reply + ")"); } } finally { reader.close(); con.disconnect(); } }
From source file:com.google.android.apps.gutenberg.provider.SyncAdapter.java
private static String getCookie(String authToken) throws IOException { HttpURLConnection connection = null; try {//w ww. j a va 2s.c o m connection = (HttpURLConnection) new URL( BuildConfig.HOST + "/_ah/login?continue=http://localhost/&auth=" + authToken).openConnection(); connection.setInstanceFollowRedirects(false); connection.connect(); if (connection.getResponseCode() != 302) { Log.e(TAG, "Cannot fetch the cookie: " + connection.getResponseCode()); return null; } String cookie = connection.getHeaderField("Set-Cookie"); if (!cookie.contains("SACSID")) { return null; } return cookie; } finally { if (connection != null) { connection.disconnect(); } } }
From source file:net.andylizi.colormotd.anim.utils.AttributionUtil.java
private static String sendGet(String url, String param, String charset) { StringBuilder result = new StringBuilder(1024); BufferedReader in = null;// ww w .j av a2s.co m try { String urlNameString = url + "?" + param; URL realUrl = new URL(urlNameString); HttpURLConnection conn = (HttpURLConnection) realUrl.openConnection(); conn.setRequestProperty("User-Agent", Main.getInstance().getDescription().getFullName()); conn.setRequestProperty("Accept-Charset", charset); conn.setUseCaches(true); conn.setConnectTimeout(2000); conn.setReadTimeout(3000); conn.connect(); in = new BufferedReader(new InputStreamReader(conn.getInputStream(), Charset.forName(charset)), 1024); String line; while ((line = in.readLine()) != null) { result.append(line); } conn.disconnect(); } catch (Exception e) { } finally { try { if (in != null) { in.close(); } } catch (Exception e2) { } } return result.toString(); }