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

The following examples show how to use java.net.httpurlconnection#getURL() . 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 File: HttpConnection.java    From astor with GNU General Public License v2.0 6 votes vote down vote up
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 2
Source File: HttpConnection.java    From astor with GNU General Public License v2.0 6 votes vote down vote up
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 3
Source File: DefaultHttpClient.java    From EserKnife with 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 4
Source File: RedirectRequestHandler.java    From LoboBrowser with 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 5
Source File: HttpConnection.java    From jsoup-learning with 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 6
Source File: HttpClientWriteRequestInterceptor.java    From skywalking with Apache License 2.0 6 votes vote down vote up
@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
Source File: ImageResponseCache.java    From FacebookNewsfeedSample-Android with Apache License 2.0 6 votes vote down vote up
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 8
Source File: ImageResponseCache.java    From aws-mobile-self-paced-labs-samples with Apache License 2.0 6 votes vote down vote up
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 9
Source File: HttpUtils.java    From commerce-gradle-plugin with Apache License 2.0 5 votes vote down vote up
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
Source File: NtlmHttpURLConnection.java    From jcifs with GNU Lesser General Public License v2.1 5 votes vote down vote up
/**
 * 
 * @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 11
Source File: HttpURLConnectionInterceptor.java    From pinpoint with Apache License 2.0 5 votes vote down vote up
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 12
Source File: Request.java    From FacebookImageShareIntent with 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 13
Source File: Request.java    From HypFacebook with BSD 2-Clause "Simplified" 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);

    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 14
Source File: Request.java    From android-skeleton-project with 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 15
Source File: HttpURLConnectionWrapper.java    From android-perftracking with MIT License 4 votes vote down vote up
public HttpURLConnectionWrapper(HttpURLConnection conn) {
  super(conn.getURL());
  _conn = conn;
}
 
Example 16
Source File: Request.java    From platform-friends-android with BSD 2-Clause "Simplified" 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);

    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 File: Request.java    From aws-mobile-self-paced-labs-samples with Apache License 2.0 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);

    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 18
Source File: ObsoleteUrlFactory.java    From DoraemonKit with Apache License 2.0 4 votes vote down vote up
DelegatingHttpsURLConnection(HttpURLConnection delegate) {
    super(delegate.getURL());
    this.delegate = delegate;
}
 
Example 19
Source File: HttpConnectionAdapter.java    From knopflerfish.org with BSD 3-Clause "New" or "Revised" License 4 votes vote down vote up
public HttpConnectionAdapter(HttpConnectionFactory factory, HttpURLConnection connection) {
   this.connection = connection;
   this.url = connection.getURL();
this.factory = factory;
factory.registerConnection(this);
 }
 
Example 20
Source File: ApigeeHttpURLConnection.java    From apigee-android-sdk with Apache License 2.0 4 votes vote down vote up
public ApigeeHttpURLConnection(HttpURLConnection connection)
{
	super(connection.getURL());
	realConnection = connection;
}