Java Code Examples for java.net.HttpURLConnection#getURL()

The following examples show how to use java.net.HttpURLConnection#getURL() . These examples are extracted from open source projects. You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may check out the related API usage on the sidebar.
Example 1
Source Project: EserKnife   File: DefaultHttpClient.java    License: Apache License 2.0 6 votes vote down vote up
protected static String getResponseAsString(HttpURLConnection conn) throws IOException{
    String charset = getResponseCharset();
    InputStream es = conn.getErrorStream();
    String msg;
    if (es == null) {
        try {
            return getStreamAsString(conn.getInputStream(), charset);
        } catch (IOException e) {
            throw new IOException(e.getMessage()+",url is "+conn.getURL());
        }
    } else {
        msg = getStreamAsString(es, charset);
        if (StringUtils.isEmpty(msg)) {

        }
    }
    return msg;
}
 
Example 2
Source Project: LoboBrowser   File: RedirectRequestHandler.java    License: MIT License 6 votes vote down vote up
/**
 *
 */
public RedirectRequestHandler(final RequestHandler origHandler, final HttpURLConnection origConnection) throws MalformedURLException {
  this.origHandler = origHandler;
  final String location = origConnection.getHeaderField("Location");
  final URL origURL = origConnection.getURL();
  if (location == null) {
    throw new IllegalArgumentException("No Location header in redirect response for " + origConnection.getURL());
  }
  final URL finalURL = org.cobraparser.util.Urls.createURL(origURL, location);
  final String origHost = origURL.getHost();
  final String finalHost = finalURL.getHost();
  if (origHost.equals(finalHost)) {
    if (origURL.getProtocol().equalsIgnoreCase(finalURL.getProtocol())) {
      if (origURL.getPort() == finalURL.getPort()) {
        final String origPath = origURL.getFile();
        final String finalPath = finalURL.getFile();
        if (origPath.equals(finalPath)) {
          throw new IllegalArgumentException("Redirecting URL '" + origURL + "' and target URL '" + finalURL + "' are equal!");
        }
      }
    }
  }
  this.latestRequestURL = finalURL;
}
 
Example 3
Source Project: jsoup-learning   File: HttpConnection.java    License: MIT License 6 votes vote down vote up
private void setupFromConnection(HttpURLConnection conn, Connection.Response previousResponse) throws IOException {
    method = Connection.Method.valueOf(conn.getRequestMethod());
    url = conn.getURL();
    statusCode = conn.getResponseCode();
    statusMessage = conn.getResponseMessage();
    contentType = conn.getContentType();

    Map<String, List<String>> resHeaders = conn.getHeaderFields();
    processResponseHeaders(resHeaders);

    // if from a redirect, map previous response cookies into this response
    if (previousResponse != null) {
        for (Map.Entry<String, String> prevCookie : previousResponse.cookies().entrySet()) {
            if (!hasCookie(prevCookie.getKey()))
                cookie(prevCookie.getKey(), prevCookie.getValue());
        }
    }
}
 
Example 4
static InputStream interceptAndCacheImageStream(Context context, HttpURLConnection connection) throws IOException {
    InputStream stream = null;
    if (connection.getResponseCode() == HttpURLConnection.HTTP_OK) {
        URL url = connection.getURL();
        stream = connection.getInputStream(); // Default stream in case caching fails
        if (isCDNURL(url)) {
            try {
                FileLruCache cache = getCache(context);

                // Wrap stream with a caching stream
                stream = cache.interceptAndPut(
                        url.toString(),
                        new BufferedHttpInputStream(stream, connection));
            } catch (IOException e) {
                // Caching is best effort
            }
        }
    }
    return stream;
}
 
Example 5
static InputStream interceptAndCacheImageStream(Context context, HttpURLConnection connection) throws IOException {
    InputStream stream = null;
    if (connection.getResponseCode() == HttpURLConnection.HTTP_OK) {
        URL url = connection.getURL();
        stream = connection.getInputStream(); // Default stream in case caching fails
        if (isCDNURL(url)) {
            try {
                FileLruCache cache = getCache(context);

                // Wrap stream with a caching stream
                stream = cache.interceptAndPut(
                        url.toString(),
                        new BufferedHttpInputStream(stream, connection));
            } catch (IOException e) {
                // Caching is best effort
            }
        }
    }
    return stream;
}
 
Example 6
@Override
public void beforeMethod(EnhancedInstance objInst, Method method, Object[] allArguments, Class<?>[] argumentsTypes,
    MethodInterceptResult result) throws Throwable {
    HttpURLConnection connection = (HttpURLConnection) objInst.getSkyWalkingDynamicField();
    MessageHeader headers = (MessageHeader) allArguments[0];
    URL url = connection.getURL();
    ContextCarrier contextCarrier = new ContextCarrier();
    AbstractSpan span = ContextManager.createExitSpan(getPath(url), contextCarrier, getPeer(url));
    span.setComponent(ComponentsDefine.JDK_HTTP);
    Tags.HTTP.METHOD.set(span, connection.getRequestMethod());
    Tags.URL.set(span, url.toString());
    SpanLayer.asHttp(span);
    CarrierItem next = contextCarrier.items();
    while (next.hasNext()) {
        next = next.next();
        headers.add(next.getHeadKey(), next.getHeadValue());
    }
}
 
Example 7
private void setupFromConnection(HttpURLConnection conn, Connection.Response previousResponse) throws IOException {
    method = Method.valueOf(conn.getRequestMethod());
    url = conn.getURL();
    statusCode = conn.getResponseCode();
    statusMessage = conn.getResponseMessage();
    contentType = conn.getContentType();

    Map<String, List<String>> resHeaders = createHeaderMap(conn);
    processResponseHeaders(resHeaders);

    // if from a redirect, map previous response cookies into this response
    if (previousResponse != null) {
        for (Map.Entry<String, String> prevCookie : previousResponse.cookies().entrySet()) {
            if (!hasCookie(prevCookie.getKey()))
                cookie(prevCookie.getKey(), prevCookie.getValue());
        }
    }
}
 
Example 8
private void setupFromConnection(HttpURLConnection conn, Connection.Response previousResponse) throws IOException {
    method = Method.valueOf(conn.getRequestMethod());
    url = conn.getURL();
    statusCode = conn.getResponseCode();
    statusMessage = conn.getResponseMessage();
    contentType = conn.getContentType();

    Map<String, List<String>> resHeaders = createHeaderMap(conn);
    processResponseHeaders(resHeaders);

    // if from a redirect, map previous response cookies into this response
    if (previousResponse != null) {
        for (Map.Entry<String, String> prevCookie : previousResponse.cookies().entrySet()) {
            if (!hasCookie(prevCookie.getKey()))
                cookie(prevCookie.getKey(), prevCookie.getValue());
        }
    }
}
 
Example 9
public static HttpURLConnection connectAndUpdateCookies(HttpURLConnection connection, CookieManager cookies, Map<String, List<String>> headers) throws Exception {
    connection.connect();
    URI uri = connection.getURL().toURI();
    cookies.put(uri, connection.getHeaderFields());
    while (isRedirect(connection)) {
        connection = followRedirect(connection, cookies, headers);
        cookies.put(connection.getURL().toURI(), connection.getHeaderFields());
    }
    if (connection.getResponseCode() > 400) {
        throw new IllegalStateException("error connecting to " + connection.getURL() + "HTTP Status: " + connection.getResponseCode());
    }
    return connection;
}
 
Example 10
private String getHost(HttpURLConnection httpURLConnection) {
    final URL url = httpURLConnection.getURL();
    if (url != null) {
        final String host = url.getHost();
        final int port = url.getPort();
        if (host != null) {
            return JdkHttpClientRequestAdaptor.getEndpoint(host, port);
        }
    }
    return null;
}
 
Example 11
/**
 * 
 * @param connection
 *            connection to wrap
 * @param tc
 *            context to use
 */
public NtlmHttpURLConnection ( HttpURLConnection connection, CIFSContext tc ) {
    super(connection.getURL());
    this.connection = connection;
    this.transportContext = tc;
    this.requestProperties = new HashMap<>();
    copySettings();
}
 
Example 12
final static void serializeToUrlConnection(RequestBatch requests, HttpURLConnection connection)
throws IOException, JSONException {
    Logger logger = new Logger(LoggingBehavior.REQUESTS, "Request");

    int numRequests = requests.size();

    HttpMethod connectionHttpMethod = (numRequests == 1) ? requests.get(0).httpMethod : HttpMethod.POST;
    connection.setRequestMethod(connectionHttpMethod.name());

    URL url = connection.getURL();
    logger.append("Request:\n");
    logger.appendKeyValue("Id", requests.getId());
    logger.appendKeyValue("URL", url);
    logger.appendKeyValue("Method", connection.getRequestMethod());
    logger.appendKeyValue("User-Agent", connection.getRequestProperty("User-Agent"));
    logger.appendKeyValue("Content-Type", connection.getRequestProperty("Content-Type"));

    connection.setConnectTimeout(requests.getTimeout());
    connection.setReadTimeout(requests.getTimeout());

    // If we have a single non-POST request, don't try to serialize anything or HttpURLConnection will
    // turn it into a POST.
    boolean isPost = (connectionHttpMethod == HttpMethod.POST);
    if (!isPost) {
        logger.log();
        return;
    }

    connection.setDoOutput(true);

    BufferedOutputStream outputStream = new BufferedOutputStream(connection.getOutputStream());
    try {
        Serializer serializer = new Serializer(outputStream, logger);

        if (numRequests == 1) {
            Request request = requests.get(0);

            logger.append("  Parameters:\n");
            serializeParameters(request.parameters, serializer);

            logger.append("  Attachments:\n");
            serializeAttachments(request.parameters, serializer);

            if (request.graphObject != null) {
                processGraphObject(request.graphObject, url.getPath(), serializer);
            }
        } else {
            String batchAppID = getBatchAppId(requests);
            if (Utility.isNullOrEmpty(batchAppID)) {
                throw new FacebookException("At least one request in a batch must have an open Session, or a "
                        + "default app ID must be specified.");
            }

            serializer.writeString(BATCH_APP_ID_PARAM, batchAppID);

            // We write out all the requests as JSON, remembering which file attachments they have, then
            // write out the attachments.
            Bundle attachments = new Bundle();
            serializeRequestsAsJSON(serializer, requests, attachments);

            logger.append("  Attachments:\n");
            serializeAttachments(attachments, serializer);
        }
    } finally {
        outputStream.close();
    }

    logger.log();
}
 
Example 13
public ApigeeHttpURLConnection(HttpURLConnection connection)
{
	super(connection.getURL());
	realConnection = connection;
}
 
Example 14
public HttpConnectionAdapter(HttpConnectionFactory factory, HttpURLConnection connection) {
   this.connection = connection;
   this.url = connection.getURL();
this.factory = factory;
factory.registerConnection(this);
 }
 
Example 15
Source Project: DoraemonKit   File: ObsoleteUrlFactory.java    License: Apache License 2.0 4 votes vote down vote up
DelegatingHttpsURLConnection(HttpURLConnection delegate) {
    super(delegate.getURL());
    this.delegate = delegate;
}
 
Example 16
final static void serializeToUrlConnection(RequestBatch requests, HttpURLConnection connection)
throws IOException, JSONException {
    Logger logger = new Logger(LoggingBehavior.REQUESTS, "Request");

    int numRequests = requests.size();

    HttpMethod connectionHttpMethod = (numRequests == 1) ? requests.get(0).httpMethod : HttpMethod.POST;
    connection.setRequestMethod(connectionHttpMethod.name());

    URL url = connection.getURL();
    logger.append("Request:\n");
    logger.appendKeyValue("Id", requests.getId());
    logger.appendKeyValue("URL", url);
    logger.appendKeyValue("Method", connection.getRequestMethod());
    logger.appendKeyValue("User-Agent", connection.getRequestProperty("User-Agent"));
    logger.appendKeyValue("Content-Type", connection.getRequestProperty("Content-Type"));

    connection.setConnectTimeout(requests.getTimeout());
    connection.setReadTimeout(requests.getTimeout());

    // If we have a single non-POST request, don't try to serialize anything or HttpURLConnection will
    // turn it into a POST.
    boolean isPost = (connectionHttpMethod == HttpMethod.POST);
    if (!isPost) {
        logger.log();
        return;
    }

    connection.setDoOutput(true);

    BufferedOutputStream outputStream = new BufferedOutputStream(connection.getOutputStream());
    try {
        Serializer serializer = new Serializer(outputStream, logger);

        if (numRequests == 1) {
            Request request = requests.get(0);

            logger.append("  Parameters:\n");
            serializeParameters(request.parameters, serializer);

            logger.append("  Attachments:\n");
            serializeAttachments(request.parameters, serializer);

            if (request.graphObject != null) {
                processGraphObject(request.graphObject, url.getPath(), serializer);
            }
        } else {
            String batchAppID = getBatchAppId(requests);
            if (Utility.isNullOrEmpty(batchAppID)) {
                throw new FacebookException("At least one request in a batch must have an open Session, or a "
                        + "default app ID must be specified.");
            }

            serializer.writeString(BATCH_APP_ID_PARAM, batchAppID);

            // We write out all the requests as JSON, remembering which file attachments they have, then
            // write out the attachments.
            Bundle attachments = new Bundle();
            serializeRequestsAsJSON(serializer, requests, attachments);

            logger.append("  Attachments:\n");
            serializeAttachments(attachments, serializer);
        }
    } finally {
        outputStream.close();
    }

    logger.log();
}
 
Example 17
Source Project: FacebookImageShareIntent   File: Request.java    License: MIT License 4 votes vote down vote up
final static void serializeToUrlConnection(RequestBatch requests, HttpURLConnection connection)
throws IOException, JSONException {
    Logger logger = new Logger(LoggingBehavior.REQUESTS, "Request");

    int numRequests = requests.size();

    HttpMethod connectionHttpMethod = (numRequests == 1) ? requests.get(0).httpMethod : HttpMethod.POST;
    connection.setRequestMethod(connectionHttpMethod.name());

    URL url = connection.getURL();
    logger.append("Request:\n");
    logger.appendKeyValue("Id", requests.getId());
    logger.appendKeyValue("URL", url);
    logger.appendKeyValue("Method", connection.getRequestMethod());
    logger.appendKeyValue("User-Agent", connection.getRequestProperty("User-Agent"));
    logger.appendKeyValue("Content-Type", connection.getRequestProperty("Content-Type"));

    connection.setConnectTimeout(requests.getTimeout());
    connection.setReadTimeout(requests.getTimeout());

    // If we have a single non-POST request, don't try to serialize anything or HttpURLConnection will
    // turn it into a POST.
    boolean isPost = (connectionHttpMethod == HttpMethod.POST);
    if (!isPost) {
        logger.log();
        return;
    }

    connection.setDoOutput(true);

    OutputStream outputStream = null;
    try {
        if (hasOnProgressCallbacks(requests)) {
            ProgressNoopOutputStream countingStream = null;
            countingStream = new ProgressNoopOutputStream(requests.getCallbackHandler());
            processRequest(requests, null, numRequests, url, countingStream);

            int max = countingStream.getMaxProgress();
            Map<Request, RequestProgress> progressMap = countingStream.getProgressMap();

            BufferedOutputStream buffered = new BufferedOutputStream(connection.getOutputStream());
            outputStream = new ProgressOutputStream(buffered, requests, progressMap, max);
        }
        else {
            outputStream = new BufferedOutputStream(connection.getOutputStream());
        }

        processRequest(requests, logger, numRequests, url, outputStream);
    }
    finally {
        outputStream.close();
    }

    logger.log();
}
 
Example 18
public HttpURLConnectionWrapper(HttpURLConnection conn) {
  super(conn.getURL());
  _conn = conn;
}
 
Example 19
Source Project: android-skeleton-project   File: Request.java    License: MIT License 4 votes vote down vote up
final static void serializeToUrlConnection(RequestBatch requests, HttpURLConnection connection)
throws IOException, JSONException {
    Logger logger = new Logger(LoggingBehavior.REQUESTS, "Request");

    int numRequests = requests.size();

    HttpMethod connectionHttpMethod = (numRequests == 1) ? requests.get(0).httpMethod : HttpMethod.POST;
    connection.setRequestMethod(connectionHttpMethod.name());

    URL url = connection.getURL();
    logger.append("Request:\n");
    logger.appendKeyValue("Id", requests.getId());
    logger.appendKeyValue("URL", url);
    logger.appendKeyValue("Method", connection.getRequestMethod());
    logger.appendKeyValue("User-Agent", connection.getRequestProperty("User-Agent"));
    logger.appendKeyValue("Content-Type", connection.getRequestProperty("Content-Type"));

    connection.setConnectTimeout(requests.getTimeout());
    connection.setReadTimeout(requests.getTimeout());

    // If we have a single non-POST request, don't try to serialize anything or HttpURLConnection will
    // turn it into a POST.
    boolean isPost = (connectionHttpMethod == HttpMethod.POST);
    if (!isPost) {
        logger.log();
        return;
    }

    connection.setDoOutput(true);

    OutputStream outputStream = null;
    try {
        if (hasOnProgressCallbacks(requests)) {
            ProgressNoopOutputStream countingStream = null;
            countingStream = new ProgressNoopOutputStream(requests.getCallbackHandler());
            processRequest(requests, null, numRequests, url, countingStream);

            int max = countingStream.getMaxProgress();
            Map<Request, RequestProgress> progressMap = countingStream.getProgressMap();

            BufferedOutputStream buffered = new BufferedOutputStream(connection.getOutputStream());
            outputStream = new ProgressOutputStream(buffered, requests, progressMap, max);
        }
        else {
            outputStream = new BufferedOutputStream(connection.getOutputStream());
        }

        processRequest(requests, logger, numRequests, url, outputStream);
    }
    finally {
        outputStream.close();
    }

    logger.log();
}
 
Example 20
final static void serializeToUrlConnection(RequestBatch requests, HttpURLConnection connection)
throws IOException, JSONException {
    Logger logger = new Logger(LoggingBehavior.REQUESTS, "Request");

    int numRequests = requests.size();

    HttpMethod connectionHttpMethod = (numRequests == 1) ? requests.get(0).httpMethod : HttpMethod.POST;
    connection.setRequestMethod(connectionHttpMethod.name());

    URL url = connection.getURL();
    logger.append("Request:\n");
    logger.appendKeyValue("Id", requests.getId());
    logger.appendKeyValue("URL", url);
    logger.appendKeyValue("Method", connection.getRequestMethod());
    logger.appendKeyValue("User-Agent", connection.getRequestProperty("User-Agent"));
    logger.appendKeyValue("Content-Type", connection.getRequestProperty("Content-Type"));

    connection.setConnectTimeout(requests.getTimeout());
    connection.setReadTimeout(requests.getTimeout());

    // If we have a single non-POST request, don't try to serialize anything or HttpURLConnection will
    // turn it into a POST.
    boolean isPost = (connectionHttpMethod == HttpMethod.POST);
    if (!isPost) {
        logger.log();
        return;
    }

    connection.setDoOutput(true);

    BufferedOutputStream outputStream = new BufferedOutputStream(connection.getOutputStream());
    try {
        Serializer serializer = new Serializer(outputStream, logger);

        if (numRequests == 1) {
            Request request = requests.get(0);

            logger.append("  Parameters:\n");
            serializeParameters(request.parameters, serializer);

            logger.append("  Attachments:\n");
            serializeAttachments(request.parameters, serializer);

            if (request.graphObject != null) {
                processGraphObject(request.graphObject, url.getPath(), serializer);
            }
        } else {
            String batchAppID = getBatchAppId(requests);
            if (Utility.isNullOrEmpty(batchAppID)) {
                throw new FacebookException("At least one request in a batch must have an open Session, or a "
                        + "default app ID must be specified.");
            }

            serializer.writeString(BATCH_APP_ID_PARAM, batchAppID);

            // We write out all the requests as JSON, remembering which file attachments they have, then
            // write out the attachments.
            Bundle attachments = new Bundle();
            serializeRequestsAsJSON(serializer, requests, attachments);

            logger.append("  Attachments:\n");
            serializeAttachments(attachments, serializer);
        }
    } finally {
        outputStream.close();
    }

    logger.log();
}