List of usage examples for java.net HttpURLConnection getURL
public URL getURL()
From source file:com.cloudant.http.interceptors.CookieInterceptor.java
@Override public HttpConnectionInterceptorContext interceptRequest(HttpConnectionInterceptorContext context) { HttpURLConnection connection = context.connection.getConnection(); if (shouldAttemptCookieRequest) { if (cookie == null) { cookie = getCookie(connection.getURL(), context); }/* ww w . ja v a 2 s . c o m*/ connection.setRequestProperty("Cookie", cookie); } return context; }
From source file:nl.ordina.bag.etl.mail.handler.HttpClient.java
private File handleResponse(HttpURLConnection connection) throws IOException { if (connection.getResponseCode() == 200) { String filename = getFilename(connection); return writeToFile(filename, connection.getInputStream()); } else/*from www .ja va 2s. c om*/ throw new IOException("Could not read file from " + connection.getURL().toString() + ". Received response code " + connection.getResponseCode()); }
From source file:com.ehsy.solr.util.SimplePostTool.java
private static boolean checkResponseCode(HttpURLConnection urlc) throws IOException { if (urlc.getResponseCode() >= 400) { warn("Solr returned an error #" + urlc.getResponseCode() + " (" + urlc.getResponseMessage() + ") for url: " + urlc.getURL()); Charset charset = StandardCharsets.ISO_8859_1; final String contentType = urlc.getContentType(); // code cloned from ContentStreamBase, but post.jar should be standalone! if (contentType != null) { int idx = contentType.toLowerCase(Locale.ROOT).indexOf("charset="); if (idx > 0) { charset = Charset.forName(contentType.substring(idx + "charset=".length()).trim()); }// w w w .ja v a 2 s.c o m } // Print the response returned by Solr try (InputStream errStream = urlc.getErrorStream()) { if (errStream != null) { BufferedReader br = new BufferedReader(new InputStreamReader(errStream, charset)); final StringBuilder response = new StringBuilder("Response: "); int ch; while ((ch = br.read()) != -1) { response.append((char) ch); } warn(response.toString().trim()); } } return false; } return true; }
From source file:com.nexmo.sdk.core.client.Client.java
/** * Executes a connection, and validates that the body was supplied. * * @param connection A prepared HttpUrlConnection. * * @return The response object./*from ww w.j av a 2 s .c o m*/ * @throws IOException If an error occurs while connecting to the resource. * @throws InternalNetworkException If an internal sdk error occurs while parsing the response. */ @Override public Response execute(HttpURLConnection connection) throws IOException, InternalNetworkException { try { connection.connect(); if (connection.getResponseCode() == HttpStatus.SC_OK) { if (BuildConfig.DEBUG) Log.d(TAG, connection.getURL().toString()); String signatureSupplied = connection.getHeaderField(BaseService.RESPONSE_SIG); Response response = new Response(getResponseString(connection.getInputStream()), signatureSupplied); if (TextUtils.isEmpty(response.getBody())) throw new InternalNetworkException(TAG + "Internal error. Body response missing."); else return response; } else throw new InternalNetworkException( TAG + " Internal error. Unable to connect to server. " + connection.getResponseCode()); } finally { connection.disconnect(); } }
From source file:com.truebanana.http.HTTPResponse.java
protected static HTTPResponse from(HTTPRequest request, HttpURLConnection connection, InputStream content) { HTTPResponse response = new HTTPResponse(); response.originalRequest = request;/* w w w. jav a 2 s .c om*/ if (content != null) { try { ByteArrayOutputStream buffer = new ByteArrayOutputStream(); byte[] data = new byte[16384]; int nRead; while ((nRead = content.read(data, 0, data.length)) != -1) { buffer.write(data, 0, nRead); } buffer.flush(); response.content = buffer.toByteArray(); } catch (IOException e) { e.printStackTrace(); } } try { response.statusCode = connection.getResponseCode(); } catch (IOException e) { } String message = null; try { message = connection.getResponseMessage(); } catch (IOException e) { message = e.getLocalizedMessage(); } response.responseMessage = response.statusCode + (message != null ? " " + message : ""); response.headers = connection.getHeaderFields(); response.requestURL = connection.getURL().toString(); return response; }
From source file:com.twitter.sdk.android.core.internal.oauth.OAuth1aServiceTest.java
@Test public void testSignRequest() throws MalformedURLException { final TwitterAuthConfig config = new TwitterAuthConfig("consumerKey", "consumerSecret"); final TwitterAuthToken accessToken = new TwitterAuthToken("token", "tokenSecret"); final HttpURLConnection connection = mock(HttpURLConnection.class); when(connection.getRequestMethod()).thenReturn("GET"); when(connection.getURL()).thenReturn(new URL("https://api.twitter.com/1.1/statuses/home_timeline.json")); OAuth1aService.signRequest(config, accessToken, connection, null); verify(connection).setRequestProperty(eq(HttpRequest.HEADER_AUTHORIZATION), any(String.class)); // TODO: Make it so that nonce and timestamp can be specified for testing puproses? }
From source file:org.opentestsystem.shared.test.interactioncontext.FastInteractionResponse.java
FastInteractionResponse(FastInteractionContext interactionContext, InputStream is, HttpURLConnection connection, long timeout, long t_timeout) throws IOException { _interactionContext = interactionContext; _timeout = timeout;/*from w ww . ja v a 2 s. co m*/ _t_timeout = t_timeout; // Get the response _requestUrl = connection.getURL(); _bytes = IOUtils.toByteArray(is); _responseHeaders = connection.getHeaderFields(); connection.getContentType(); String message = connection.getResponseMessage(); if (message != null) { String[] messageParts = StringUtils.split(message, null, 3); if (messageParts.length > 0) { _httpVersion = messageParts[0]; } if (messageParts.length > 1) { try { _status = Integer.valueOf(messageParts[1]); } catch (Exception e) { // Do nothing: an invalid HTTP status code!! } } if (messageParts.length > 2) { _statusMessage = messageParts[2]; } } }
From source file:org.openmrs.module.ModuleUtil.java
/** * Convenience method to follow http to https redirects. Will follow a total of 5 redirects, * then fail out due to foolishness on the url's part. * * @param c the {@link URLConnection} to open * @return an {@link InputStream} that is not necessarily at the same url, possibly at a 403 * redirect./*from ww w .ja v a2 s.com*/ * @throws IOException * @see #getURLStream(URL) */ protected static InputStream openConnectionCheckRedirects(URLConnection c) throws IOException { boolean redir; int redirects = 0; InputStream in = null; do { if (c instanceof HttpURLConnection) { ((HttpURLConnection) c).setInstanceFollowRedirects(false); } // We want to open the input stream before getting headers // because getHeaderField() et al swallow IOExceptions. in = c.getInputStream(); redir = false; if (c instanceof HttpURLConnection) { HttpURLConnection http = (HttpURLConnection) c; int stat = http.getResponseCode(); if (stat == 300 || stat == 301 || stat == 302 || stat == 303 || stat == 305 || stat == 307) { URL base = http.getURL(); String loc = http.getHeaderField("Location"); URL target = null; if (loc != null) { target = new URL(base, loc); } http.disconnect(); // Redirection should be allowed only for HTTP and HTTPS // and should be limited to 5 redirections at most. if (target == null || !("http".equals(target.getProtocol()) || "https".equals(target.getProtocol())) || redirects >= 5) { throw new SecurityException("illegal URL redirect"); } redir = true; c = target.openConnection(); redirects++; } } } while (redir); return in; }
From source file:org.onebusaway.admin.service.impl.RemoteConnectionServiceImpl.java
private String fromJson(HttpURLConnection connection) { try {/* w w w . j a v a2s . c o m*/ ByteArrayOutputStream baos = new ByteArrayOutputStream(); IOUtils.copy(connection.getInputStream(), baos); return baos.toString(); } catch (IOException e) { log.error("fromJson caught exception for url (" + connection.getURL() + "):", e); e.printStackTrace(); } return null; }
From source file:com.facebook.GraphRequestTest.java
@Test public void testSingleGetToHttpRequest() throws Exception { GraphRequest requestMe = new GraphRequest(null, "TourEiffel"); HttpURLConnection connection = GraphRequest.toHttpConnection(requestMe); assertTrue(connection != null);//w w w . java2s .co m assertEquals("GET", connection.getRequestMethod()); assertEquals("/" + ServerProtocol.getAPIVersion() + "/TourEiffel", connection.getURL().getPath()); assertTrue(connection.getRequestProperty("User-Agent").startsWith("FBAndroidSDK")); Uri uri = Uri.parse(connection.getURL().toString()); assertEquals("android", uri.getQueryParameter("sdk")); assertEquals("json", uri.getQueryParameter("format")); }