下面列出了java.net.HttpURLConnection#getURL ( ) 实例代码,或者点击链接到github查看源代码,也可以在右侧发表评论。
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;
}
/**
*
*/
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;
}
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());
}
}
}
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;
}
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;
}
@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());
}
}
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());
}
}
}
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());
}
}
}
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;
}
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;
}
/**
*
* @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();
}
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();
}
public ApigeeHttpURLConnection(HttpURLConnection connection)
{
super(connection.getURL());
realConnection = connection;
}
public HttpConnectionAdapter(HttpConnectionFactory factory, HttpURLConnection connection) {
this.connection = connection;
this.url = connection.getURL();
this.factory = factory;
factory.registerConnection(this);
}
DelegatingHttpsURLConnection(HttpURLConnection delegate) {
super(delegate.getURL());
this.delegate = delegate;
}
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();
}
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();
}
public HttpURLConnectionWrapper(HttpURLConnection conn) {
super(conn.getURL());
_conn = conn;
}
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();
}
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();
}