1
0
mirror of https://github.com/etesync/android synced 2024-11-22 07:58:09 +00:00

First use of dav4android for resource detection

* replaced Apache httplib by gradle version because it will be removed completely anyway
This commit is contained in:
Ricki Hirner 2015-10-10 02:15:01 +02:00
parent d0b928a93d
commit 0bc1a8178a
371 changed files with 191 additions and 45980 deletions

3
.gitmodules vendored Normal file
View File

@ -0,0 +1,3 @@
[submodule "dav4android"]
path = dav4android
url = git@gitlab.com:bitfireAT/dav4android.git

View File

@ -9,13 +9,14 @@
apply plugin: 'com.android.application'
android {
compileSdkVersion 22
buildToolsVersion '22.0.1'
compileSdkVersion 23
buildToolsVersion '23.0.1'
useLibrary 'org.apache.http.legacy'
defaultConfig {
applicationId "at.bitfire.davdroid"
minSdkVersion 14
targetSdkVersion 22
targetSdkVersion 23
}
buildTypes {
@ -66,11 +67,13 @@ dependencies {
// dnsjava for querying SRV/TXT records
compile 'dnsjava:dnsjava:2.1.7'
// HttpClient 4.3, Android flavour for WebDAV operations
//compile 'org.apache.httpcomponents:httpclient-android:4.3.5.1'
compile project(':lib:httpclient-android')
compile 'org.apache.httpcomponents:httpclient-android:4.3.5.1'
//compile project(':lib:httpclient-android')
// SimpleXML for parsing and generating WebDAV messages
compile('org.simpleframework:simple-xml:2.7.1') {
exclude group: 'stax', module: 'stax-api'
exclude group: 'xpp3', module: 'xpp3'
}
compile project(':dav4android')
}

View File

@ -12,10 +12,6 @@
android:versionCode="72" android:versionName="0.8.4.1"
android:installLocation="internalOnly">
<uses-sdk
android:minSdkVersion="14"
android:targetSdkVersion="22" />
<uses-permission android:name="android.permission.INTERNET" />
<uses-permission android:name="android.permission.AUTHENTICATE_ACCOUNTS" />
<uses-permission android:name="android.permission.GET_ACCOUNTS" />

View File

@ -9,6 +9,9 @@ package at.bitfire.davdroid;
import net.fortuna.ical4j.model.property.ProdId;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
public class Constants {
public static final String
APP_VERSION = "0.8.4.1",
@ -18,4 +21,6 @@ public class Constants {
WEB_URL_VIEW_LOGS = "https://github.com/bitfireAT/davdroid/wiki/How-to-view-the-logs";
public static final ProdId ICAL_PRODID = new ProdId("-//bitfire web engineering//DAVdroid " + Constants.APP_VERSION + " (ical4j 2.0-beta1)//EN");
public static final Logger log = LoggerFactory.getLogger("DAVdroid");
}

View File

@ -8,10 +8,11 @@
package at.bitfire.davdroid.resource;
import android.content.Context;
import android.text.TextUtils;
import android.util.Log;
import org.apache.http.HttpException;
import org.apache.http.impl.client.CloseableHttpClient;
import com.squareup.okhttp.HttpUrl;
import org.xbill.DNS.Lookup;
import org.xbill.DNS.Record;
import org.xbill.DNS.SRVRecord;
@ -19,161 +20,137 @@ import org.xbill.DNS.TXTRecord;
import org.xbill.DNS.TextParseException;
import org.xbill.DNS.Type;
import java.io.Closeable;
import java.io.IOException;
import java.net.URI;
import java.net.URISyntaxException;
import java.util.LinkedList;
import java.util.List;
import at.bitfire.davdroid.R;
import at.bitfire.davdroid.webdav.DavException;
import at.bitfire.davdroid.webdav.DavHttpClient;
import at.bitfire.davdroid.webdav.DavIncapableException;
import at.bitfire.davdroid.webdav.HttpPropfind.Mode;
import at.bitfire.davdroid.webdav.NotAuthorizedException;
import at.bitfire.davdroid.webdav.WebDavResource;
import at.bitfire.dav4android.DavResource;
import at.bitfire.dav4android.HttpClient;
import at.bitfire.dav4android.exception.DavException;
import at.bitfire.dav4android.exception.HttpException;
import at.bitfire.dav4android.property.AddressbookDescription;
import at.bitfire.dav4android.property.AddressbookHomeSet;
import at.bitfire.dav4android.property.CalendarColor;
import at.bitfire.dav4android.property.CalendarDescription;
import at.bitfire.dav4android.property.CalendarHomeSet;
import at.bitfire.dav4android.property.CurrentUserPrincipal;
import at.bitfire.dav4android.property.DisplayName;
import at.bitfire.dav4android.property.ResourceType;
import at.bitfire.davdroid.Constants;
import at.bitfire.davdroid.DAVUtils;
public class DavResourceFinder implements Closeable {
public class DavResourceFinder {
private final static String TAG = "davdroid.ResourceFinder";
final protected Context context;
final protected CloseableHttpClient httpClient;
public DavResourceFinder(Context context) {
this.context = context;
// disable compression and enable network logging for debugging purposes
httpClient = DavHttpClient.create();
}
@Override
public void close() throws IOException {
httpClient.close();
}
public void findResources(final ServerInfo serverInfo) throws URISyntaxException, IOException, HttpException, DavException {
final HttpClient httpClient = new HttpClient();
/*httpClient.setAuthenticator(new Authenticator() {
@Override
public Request authenticate(Proxy proxy, Response response) throws IOException {
String credential = Credentials.basic(serverInfo.getUserName(), serverInfo.getPassword());
return response.request().newBuilder()
.header("Authorization", credential)
.build();
}
@Override
public Request authenticateProxy(Proxy proxy, Response response) throws IOException {
return null;
}
});*/
public void findResources(ServerInfo serverInfo) throws URISyntaxException, DavException, HttpException, IOException {
// CardDAV
Log.i(TAG, "*** Starting CardDAV resource detection");
WebDavResource principal = getCurrentUserPrincipal(serverInfo, "carddav");
URI uriAddressBookHomeSet = null;
try {
principal.propfind(Mode.HOME_SETS);
uriAddressBookHomeSet = principal.getProperties().getAddressbookHomeSet();
} catch (Exception e) {
Log.i(TAG, "Couldn't find address-book home set", e);
}
if (uriAddressBookHomeSet != null) {
Log.i(TAG, "Found address-book home set: " + uriAddressBookHomeSet);
// CardDAV
Constants.log.info("*** CardDAV resource detection ***");
HttpUrl principalUrl = getCurrentUserPrincipal(httpClient, serverInfo, "carddav");
WebDavResource homeSetAddressBooks = new WebDavResource(principal, uriAddressBookHomeSet);
if (checkHomesetCapabilities(homeSetAddressBooks, "addressbook")) {
serverInfo.setCardDAV(true);
homeSetAddressBooks.propfind(Mode.CARDDAV_COLLECTIONS);
DavResource principal = new DavResource(httpClient, principalUrl);
principal.propfind(0, AddressbookHomeSet.NAME);
AddressbookHomeSet addrHomeSet = (AddressbookHomeSet)principal.properties.get(AddressbookHomeSet.NAME);
if (addrHomeSet != null && !addrHomeSet.hrefs.isEmpty()) {
Constants.log.info("Found addressbook home set(s): " + addrHomeSet);
serverInfo.setCardDAV(true);
List<WebDavResource> possibleAddressBooks = new LinkedList<>();
possibleAddressBooks.add(homeSetAddressBooks);
if (homeSetAddressBooks.getMembers() != null)
possibleAddressBooks.addAll(homeSetAddressBooks.getMembers());
// enumerate address books
List<ServerInfo.ResourceInfo> addressBooks = new LinkedList<>();
for (String href : addrHomeSet.hrefs) {
DavResource homeSet = new DavResource(httpClient, principalUrl.resolve(href));
homeSet.propfind(1, ResourceType.NAME, DisplayName.NAME, AddressbookDescription.NAME);
for (DavResource member : homeSet.members) {
ResourceType type = (ResourceType)member.properties.get(ResourceType.NAME);
if (type != null && type.types.contains(ResourceType.ADDRESSBOOK)) {
Constants.log.info("Found address book: " + member.location);
List<ServerInfo.ResourceInfo> addressBooks = new LinkedList<>();
for (WebDavResource resource : possibleAddressBooks) {
final WebDavResource.Properties properties = resource.getProperties();
if (properties.isAddressBook()) {
Log.i(TAG, "Found address book: " + resource.getLocation().getPath());
ServerInfo.ResourceInfo info = new ServerInfo.ResourceInfo(
ServerInfo.ResourceInfo.Type.ADDRESS_BOOK,
properties.isReadOnly(),
resource.getLocation().toString(),
properties.getDisplayName(),
properties.getDescription(), properties.getColor()
);
DisplayName displayName = (DisplayName)member.properties.get(DisplayName.NAME);
AddressbookDescription description = (AddressbookDescription)member.properties.get(AddressbookDescription.NAME);
addressBooks.add(info);
}
}
serverInfo.setAddressBooks(addressBooks);
} else
Log.w(TAG, "Found address-book home set, but it doesn't advertise CardDAV support");
}
// TODO read-only
// CalDAV
Log.i(TAG, "*** Starting CalDAV resource detection");
principal = getCurrentUserPrincipal(serverInfo, "caldav");
URI uriCalendarHomeSet = null;
try {
principal.propfind(Mode.HOME_SETS);
uriCalendarHomeSet = principal.getProperties().getCalendarHomeSet();
} catch(Exception e) {
Log.i(TAG, "Couldn't find calendar home set", e);
}
if (uriCalendarHomeSet != null) {
Log.i(TAG, "Found calendar home set: " + uriCalendarHomeSet);
addressBooks.add(new ServerInfo.ResourceInfo(
ServerInfo.ResourceInfo.Type.ADDRESS_BOOK,
false,
member.location.toString(),
displayName != null ? displayName.displayName : null,
description != null ? description.description : null,
null
));
}
}
}
serverInfo.setAddressBooks(addressBooks);
}
WebDavResource homeSetCalendars = new WebDavResource(principal, uriCalendarHomeSet);
if (checkHomesetCapabilities(homeSetCalendars, "calendar-access")) {
serverInfo.setCalDAV(true);
homeSetCalendars.propfind(Mode.CALDAV_COLLECTIONS);
// CalDAV
Constants.log.info("*** CalDAV resource detection ***");
principalUrl = getCurrentUserPrincipal(httpClient, serverInfo, "caldav");
List<WebDavResource> possibleCalendars = new LinkedList<>();
possibleCalendars.add(homeSetCalendars);
if (homeSetCalendars.getMembers() != null)
possibleCalendars.addAll(homeSetCalendars.getMembers());
principal = new DavResource(httpClient, principalUrl);
principal.propfind(0, CalendarHomeSet.NAME);
CalendarHomeSet calHomeSet = (CalendarHomeSet)principal.properties.get(CalendarHomeSet.NAME);
if (calHomeSet != null && !calHomeSet.hrefs.isEmpty()) {
Constants.log.info("Found calendar home set(s): " + calHomeSet);
serverInfo.setCalDAV(true);
List<ServerInfo.ResourceInfo>
calendars = new LinkedList<>(),
todoLists = new LinkedList<>();
for (WebDavResource resource : possibleCalendars) {
final WebDavResource.Properties properties = resource.getProperties();
if (properties.isCalendar()) {
Log.i(TAG, "Found calendar: " + resource.getLocation().getPath());
ServerInfo.ResourceInfo info = new ServerInfo.ResourceInfo(
ServerInfo.ResourceInfo.Type.CALENDAR,
properties.isReadOnly(),
resource.getLocation().toString(),
properties.getDisplayName(),
properties.getDescription(), properties.getColor()
);
info.setTimezone(properties.getTimeZone());
// enumerate address books
List<ServerInfo.ResourceInfo> calendars = new LinkedList<>();
for (String href : calHomeSet.hrefs) {
DavResource homeSet = new DavResource(httpClient, principalUrl.resolve(href));
homeSet.propfind(1, ResourceType.NAME, DisplayName.NAME, CalendarDescription.NAME, CalendarColor.NAME);
for (DavResource member : homeSet.members) {
ResourceType type = (ResourceType)member.properties.get(ResourceType.NAME);
if (type != null && type.types.contains(ResourceType.CALENDAR)) {
Constants.log.info("Found calendar: " + member.location);
boolean isCalendar = false,
isTodoList = false;
if (properties.getSupportedComponents() == null) {
// no info about supported components, assuming all components are supported
isCalendar = true;
isTodoList = true;
} else {
// CALDAV:supported-calendar-component-set available
for (String supportedComponent : properties.getSupportedComponents())
if ("VEVENT".equalsIgnoreCase(supportedComponent))
isCalendar = true;
else if ("VTODO".equalsIgnoreCase(supportedComponent))
isTodoList = true;
DisplayName displayName = (DisplayName)member.properties.get(DisplayName.NAME);
CalendarDescription description = (CalendarDescription)member.properties.get(CalendarDescription.NAME);
CalendarColor color = (CalendarColor)member.properties.get(CalendarColor.NAME);
if (!isCalendar && !isTodoList) {
Log.i(TAG, "Ignoring this calendar because it supports neither VEVENT nor VTODO");
continue;
}
}
// TODO read-only, time-zone, supported components
// use a copy constructor to allow different "enabled" status for calendars and todo lists
if (isCalendar)
calendars.add(new ServerInfo.ResourceInfo(info));
if (isTodoList)
todoLists.add(new ServerInfo.ResourceInfo(info));
}
}
calendars.add(new ServerInfo.ResourceInfo(
ServerInfo.ResourceInfo.Type.ADDRESS_BOOK,
false,
member.location.toString(),
displayName != null ? displayName.displayName : null,
description != null ? description.description : null,
color != null ? DAVUtils.CalDAVtoARGBColor(color.color) : null
));
}
}
}
serverInfo.setCalendars(calendars);
}
serverInfo.setCalendars(calendars);
serverInfo.setTodoLists(todoLists);
} else
Log.w(TAG, "Found calendar home set, but it doesn't advertise CalDAV support");
}
if (!serverInfo.isCalDAV() && !serverInfo.isCardDAV())
throw new DavIncapableException(context.getString(R.string.setup_neither_caldav_nor_carddav));
/*if (!serverInfo.isCalDAV() && !serverInfo.isCardDAV())
throw new DavIncapableException(context.getString(R.string.setup_neither_caldav_nor_carddav));*/
}
@ -184,7 +161,7 @@ public class DavResourceFinder implements Closeable {
* @return Initial service URL (HTTP/HTTPS), without user credentials
* @throws URISyntaxException when the user-given URI is invalid
*/
public URI getInitialContextURL(ServerInfo serverInfo, String serviceName) throws URISyntaxException {
public HttpUrl getInitialContextURL(ServerInfo serverInfo, String serviceName) throws URISyntaxException {
String scheme,
domain;
int port = -1;
@ -215,7 +192,7 @@ public class DavResourceFinder implements Closeable {
// try to determine FQDN and port number using SRV records
try {
String name = "_" + serviceName + "s._tcp." + domain;
Log.d(TAG, "Looking up SRV records for " + name);
Constants.log.debug("Looking up SRV records for " + name);
Record[] records = new Lookup(name, Type.SRV).run();
if (records != null && records.length >= 1) {
SRVRecord srv = selectSRVRecord(records);
@ -225,9 +202,6 @@ public class DavResourceFinder implements Closeable {
port = srv.getPort();
Log.d(TAG, "Found " + serviceName + "s service for " + domain + " -> " + domain + ":" + port);
if (port == 443) // no reason to explicitly give the default port
port = -1;
// SRV record found, look for TXT record too (for initial context path)
records = new Lookup(name, Type.TXT).run();
if (records != null && records.length >= 1) {
@ -236,7 +210,7 @@ public class DavResourceFinder implements Closeable {
String segment = (String)o;
if (segment.startsWith("path=")) {
path = segment.substring(5);
Log.d(TAG, "Found initial context path for " + serviceName + " at " + domain + " -> " + path);
Constants.log.debug("Found initial context path for " + serviceName + " at " + domain + " -> " + path);
break;
}
}
@ -246,7 +220,12 @@ public class DavResourceFinder implements Closeable {
throw new URISyntaxException(domain, "Invalid domain name");
}
return new URI(scheme, null, domain, port, path, null, null);
HttpUrl.Builder builder = new HttpUrl.Builder().scheme(scheme).host(domain);
if (port != -1)
builder.port(port);
if (TextUtils.isEmpty(path))
path = "/";
return builder.encodedPath(path).build();
}
@ -256,77 +235,57 @@ public class DavResourceFinder implements Closeable {
* is tried.
* @param serverInfo Location that will be queried
* @param serviceName Well-known service name ("carddav", "caldav")
* @return WebDavResource of current-user-principal for the given service, or null if it can't be found
* @return WebDavResource of current-user-principal for the given service, or initial context URL if it can't be found
*
* TODO: If a TXT record is given, always use it instead of trying .well-known first
*/
WebDavResource getCurrentUserPrincipal(ServerInfo serverInfo, String serviceName) throws URISyntaxException, IOException, NotAuthorizedException {
URI initialURL = getInitialContextURL(serverInfo, serviceName);
if (initialURL != null) {
Log.i(TAG, "Looking up principal URL for service " + serviceName + "; initial context: " + initialURL);
HttpUrl getCurrentUserPrincipal(HttpClient httpClient, ServerInfo serverInfo, String serviceName) throws URISyntaxException {
HttpUrl initialURL = getInitialContextURL(serverInfo, serviceName);
// determine base URL (host name and initial context path)
WebDavResource base = new WebDavResource(httpClient,
initialURL,
serverInfo.getUserName(), serverInfo.getPassword(), serverInfo.isAuthPreemptive());
if (initialURL != null) {
Constants.log.info("Looking up principal URL for service " + serviceName + "; initial context: " + initialURL);
// look for well-known service (RFC 5785)
try {
WebDavResource wellKnown = new WebDavResource(base, new URI("/.well-known/" + serviceName));
wellKnown.propfind(Mode.CURRENT_USER_PRINCIPAL);
if (wellKnown.getProperties().getCurrentUserPrincipal() != null) {
URI principal = wellKnown.getProperties().getCurrentUserPrincipal();
Log.i(TAG, "Principal URL found from Well-Known URI: " + principal);
return new WebDavResource(wellKnown, principal);
}
} catch (NotAuthorizedException e) {
Log.w(TAG, "Not authorized for well-known " + serviceName + " service detection", e);
throw e;
} catch (URISyntaxException e) {
Log.e(TAG, "Well-known" + serviceName + " service detection failed because of invalid URIs", e);
} catch (HttpException e) {
Log.d(TAG, "Well-known " + serviceName + " service detection failed with HTTP error", e);
} catch (DavException e) {
Log.w(TAG, "Well-known " + serviceName + " service detection failed with unexpected DAV response", e);
} catch (IOException e) {
Log.e(TAG, "Well-known " + serviceName + " service detection failed with I/O error", e);
}
// look for well-known service (RFC 5785)
try {
DavResource wellKnown = new DavResource(httpClient, initialURL.resolve("/.well-known/" + serviceName));
wellKnown.propfind(0, CurrentUserPrincipal.NAME);
// fall back to user-given initial context path
Log.d(TAG, "Well-known service detection failed, trying initial context path " + initialURL);
try {
base.propfind(Mode.CURRENT_USER_PRINCIPAL);
if (base.getProperties().getCurrentUserPrincipal() != null) {
URI principal = base.getProperties().getCurrentUserPrincipal();
Log.i(TAG, "Principal URL found from initial context path: " + principal);
return new WebDavResource(base, principal);
}
} catch (NotAuthorizedException e) {
Log.e(TAG, "Not authorized for querying principal", e);
throw e;
} catch (HttpException e) {
Log.e(TAG, "HTTP error when querying principal", e);
} catch (DavException e) {
Log.e(TAG, "DAV error when querying principal", e);
}
CurrentUserPrincipal principal = (CurrentUserPrincipal)wellKnown.properties.get(CurrentUserPrincipal.NAME);
if (principal != null) {
HttpUrl url = wellKnown.location.resolve(principal.href);
Constants.log.info("Found principal URL from well-known URL: " + url);
return url;
}
} catch (IOException e) {
Constants.log.warn("Well-known " + serviceName + " service detection failed with I/O error", e);
} catch (HttpException e) {
Constants.log.warn("Well-known " + serviceName + " service detection failed with HTTP error", e);
} catch (DavException e) {
Constants.log.warn("Well-known " + serviceName + " service detection failed with DAV error", e);
}
}
Log.i(TAG, "Couldn't find current-user-principal for service " + serviceName + ", assuming initial context path is principal path");
return base;
}
return null;
}
// fall back to user-given initial context path
Log.d(TAG, "Well-known service detection failed, trying initial context path " + initialURL);
try {
DavResource base = new DavResource(httpClient, initialURL);
base.propfind(0, CurrentUserPrincipal.NAME);
CurrentUserPrincipal principal = (CurrentUserPrincipal)base.properties.get(CurrentUserPrincipal.NAME);
if (principal != null) {
HttpUrl url = base.location.resolve(principal.href);
Constants.log.info("Found principal URL from initial context URL: " + url);
return url;
}
} catch (IOException e) {
Constants.log.warn("Well-known " + serviceName + " service detection failed with I/O error", e);
} catch (HttpException e) {
Log.e(TAG, "HTTP error when querying principal", e);
} catch (DavException e) {
Log.e(TAG, "DAV error when querying principal", e);
}
public static boolean checkHomesetCapabilities(WebDavResource resource, String davCapability) throws URISyntaxException, IOException {
// check for necessary capabilities
try {
resource.options();
if (resource.supportsDAV(davCapability) &&
resource.supportsMethod("PROPFIND")) // check only for methods that MUST be available for home sets
return true;
} catch(HttpException e) {
// for instance, 405 Method not allowed
}
return false;
Log.i(TAG, "Couldn't find current-user-principal for service " + serviceName + ". Assuming principal path is initial context path!");
return initialURL;
}

View File

@ -21,19 +21,18 @@ import android.view.ViewGroup;
import android.widget.Toast;
import org.apache.commons.lang3.exception.ExceptionUtils;
import org.apache.http.HttpException;
import java.io.IOException;
import java.net.URI;
import java.net.URISyntaxException;
import java.security.cert.CertPathValidatorException;
import at.bitfire.dav4android.exception.DavException;
import at.bitfire.dav4android.exception.HttpException;
import at.bitfire.davdroid.R;
import at.bitfire.davdroid.resource.DavResourceFinder;
import at.bitfire.davdroid.resource.LocalTaskList;
import at.bitfire.davdroid.resource.ServerInfo;
import at.bitfire.davdroid.webdav.DavException;
import lombok.Cleanup;
public class QueryServerDialogFragment extends DialogFragment implements LoaderCallbacks<ServerInfo> {
private static final String TAG = "davdroid.QueryServer";
@ -113,7 +112,7 @@ public class QueryServerDialogFragment extends DialogFragment implements LoaderC
);
try {
@Cleanup DavResourceFinder finder = new DavResourceFinder(context);
DavResourceFinder finder = new DavResourceFinder(context);
finder.findResources(serverInfo);
} catch (URISyntaxException e) {
serverInfo.setErrorMessage(getContext().getString(R.string.exception_uri_syntax, e.getMessage()));
@ -127,9 +126,9 @@ public class QueryServerDialogFragment extends DialogFragment implements LoaderC
Log.e(TAG, "HTTP error while querying server info", e);
serverInfo.setErrorMessage(getContext().getString(R.string.exception_http, e.getLocalizedMessage()));
} catch (DavException e) {
Log.e(TAG, "DAV error while querying server info", e);
serverInfo.setErrorMessage(getContext().getString(R.string.exception_incapable_resource, e.getLocalizedMessage()));
}
Log.e(TAG, "DAV error while querying server info", e);
serverInfo.setErrorMessage(getContext().getString(R.string.exception_incapable_resource, e.getLocalizedMessage()));
}
return serverInfo;
}

View File

@ -12,13 +12,15 @@ buildscript {
jcenter()
}
dependencies {
classpath 'com.android.tools.build:gradle:1.0.1'
classpath 'com.android.tools.build:gradle:1.3.1'
}
}
allprojects {
repositories {
jcenter()
mavenCentral()
maven {
url 'http://oss.sonatype.org/content/repositories/snapshots'
}
}
}

1
dav4android Submodule

@ -0,0 +1 @@
Subproject commit c8dffb7fa114a3ca46917ac18088cda981f0afd5

Binary file not shown.

View File

@ -1,14 +1,6 @@
#
# Copyright (c) 2013 2015 Ricki Hirner (bitfire web engineering).
# All rights reserved. This program and the accompanying materials
# are made available under the terms of the GNU Public License v3.0
# which accompanies this distribution, and is available at
# http://www.gnu.org/licenses/gpl.html
#
#Wed Apr 10 15:27:10 PDT 2013
#Fri Oct 09 23:40:23 CEST 2015
distributionBase=GRADLE_USER_HOME
distributionPath=wrapper/dists
zipStoreBase=GRADLE_USER_HOME
zipStorePath=wrapper/dists
distributionUrl=https\://services.gradle.org/distributions/gradle-2.2.1-all.zip
distributionUrl=https\://services.gradle.org/distributions/gradle-2.2.1-bin.zip

View File

@ -1,39 +0,0 @@
Building HttpComponents Client for Android
============================
(1) Requisites
--------------
Android SDK rev. 17 (4.2.2 or Jelly Bean MR1) or newer is required in order
to compile HttpClient for Android. Android SDK can be downloaded either separately
or bundled with Android Studio.
HttpClient for Android utilizes Gradle as a building and packaging tool.
Version 2.2.1 or later is recommended.
Gradle installation and configuration instructions can be found here:
http://www.gradle.org/
(2) Building artifacts
Set environmental variable ANDROID_HOME to the location of the Android SDK.
Execute the following command in order to build binary, source and javadoc artifacts.
gradle -q assemble
Please note that when building a release version (project version does not have
'-SNAPSHOT' qualifier) one must also provide signing key details in gradle.properties
file in order to be able to sign the artifacts and successfully build the release.
---
signing.keyId=AEAEAEAE
signing.secretKeyRingFile=~/.gnupg/secring.gpg
---
The artifacts can be found in the 'build/libs' folder
build/libs/httpclient-android-<VERSION>.jar
build/libs/httpclient-android-<VERSION>-javadoc.jar
build/libs/httpclient-android-<VERSION>-sources.jar

View File

@ -1,241 +0,0 @@
Apache License
Version 2.0, January 2004
http://www.apache.org/licenses/
TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION
1. Definitions.
"License" shall mean the terms and conditions for use, reproduction,
and distribution as defined by Sections 1 through 9 of this document.
"Licensor" shall mean the copyright owner or entity authorized by
the copyright owner that is granting the License.
"Legal Entity" shall mean the union of the acting entity and all
other entities that control, are controlled by, or are under common
control with that entity. For the purposes of this definition,
"control" means (i) the power, direct or indirect, to cause the
direction or management of such entity, whether by contract or
otherwise, or (ii) ownership of fifty percent (50%) or more of the
outstanding shares, or (iii) beneficial ownership of such entity.
"You" (or "Your") shall mean an individual or Legal Entity
exercising permissions granted by this License.
"Source" form shall mean the preferred form for making modifications,
including but not limited to software source code, documentation
source, and configuration files.
"Object" form shall mean any form resulting from mechanical
transformation or translation of a Source form, including but
not limited to compiled object code, generated documentation,
and conversions to other media types.
"Work" shall mean the work of authorship, whether in Source or
Object form, made available under the License, as indicated by a
copyright notice that is included in or attached to the work
(an example is provided in the Appendix below).
"Derivative Works" shall mean any work, whether in Source or Object
form, that is based on (or derived from) the Work and for which the
editorial revisions, annotations, elaborations, or other modifications
represent, as a whole, an original work of authorship. For the purposes
of this License, Derivative Works shall not include works that remain
separable from, or merely link (or bind by name) to the interfaces of,
the Work and Derivative Works thereof.
"Contribution" shall mean any work of authorship, including
the original version of the Work and any modifications or additions
to that Work or Derivative Works thereof, that is intentionally
submitted to Licensor for inclusion in the Work by the copyright owner
or by an individual or Legal Entity authorized to submit on behalf of
the copyright owner. For the purposes of this definition, "submitted"
means any form of electronic, verbal, or written communication sent
to the Licensor or its representatives, including but not limited to
communication on electronic mailing lists, source code control systems,
and issue tracking systems that are managed by, or on behalf of, the
Licensor for the purpose of discussing and improving the Work, but
excluding communication that is conspicuously marked or otherwise
designated in writing by the copyright owner as "Not a Contribution."
"Contributor" shall mean Licensor and any individual or Legal Entity
on behalf of whom a Contribution has been received by Licensor and
subsequently incorporated within the Work.
2. Grant of Copyright License. Subject to the terms and conditions of
this License, each Contributor hereby grants to You a perpetual,
worldwide, non-exclusive, no-charge, royalty-free, irrevocable
copyright license to reproduce, prepare Derivative Works of,
publicly display, publicly perform, sublicense, and distribute the
Work and such Derivative Works in Source or Object form.
3. Grant of Patent License. Subject to the terms and conditions of
this License, each Contributor hereby grants to You a perpetual,
worldwide, non-exclusive, no-charge, royalty-free, irrevocable
(except as stated in this section) patent license to make, have made,
use, offer to sell, sell, import, and otherwise transfer the Work,
where such license applies only to those patent claims licensable
by such Contributor that are necessarily infringed by their
Contribution(s) alone or by combination of their Contribution(s)
with the Work to which such Contribution(s) was submitted. If You
institute patent litigation against any entity (including a
cross-claim or counterclaim in a lawsuit) alleging that the Work
or a Contribution incorporated within the Work constitutes direct
or contributory patent infringement, then any patent licenses
granted to You under this License for that Work shall terminate
as of the date such litigation is filed.
4. Redistribution. You may reproduce and distribute copies of the
Work or Derivative Works thereof in any medium, with or without
modifications, and in Source or Object form, provided that You
meet the following conditions:
(a) You must give any other recipients of the Work or
Derivative Works a copy of this License; and
(b) You must cause any modified files to carry prominent notices
stating that You changed the files; and
(c) You must retain, in the Source form of any Derivative Works
that You distribute, all copyright, patent, trademark, and
attribution notices from the Source form of the Work,
excluding those notices that do not pertain to any part of
the Derivative Works; and
(d) If the Work includes a "NOTICE" text file as part of its
distribution, then any Derivative Works that You distribute must
include a readable copy of the attribution notices contained
within such NOTICE file, excluding those notices that do not
pertain to any part of the Derivative Works, in at least one
of the following places: within a NOTICE text file distributed
as part of the Derivative Works; within the Source form or
documentation, if provided along with the Derivative Works; or,
within a display generated by the Derivative Works, if and
wherever such third-party notices normally appear. The contents
of the NOTICE file are for informational purposes only and
do not modify the License. You may add Your own attribution
notices within Derivative Works that You distribute, alongside
or as an addendum to the NOTICE text from the Work, provided
that such additional attribution notices cannot be construed
as modifying the License.
You may add Your own copyright statement to Your modifications and
may provide additional or different license terms and conditions
for use, reproduction, or distribution of Your modifications, or
for any such Derivative Works as a whole, provided Your use,
reproduction, and distribution of the Work otherwise complies with
the conditions stated in this License.
5. Submission of Contributions. Unless You explicitly state otherwise,
any Contribution intentionally submitted for inclusion in the Work
by You to the Licensor shall be under the terms and conditions of
this License, without any additional terms or conditions.
Notwithstanding the above, nothing herein shall supersede or modify
the terms of any separate license agreement you may have executed
with Licensor regarding such Contributions.
6. Trademarks. This License does not grant permission to use the trade
names, trademarks, service marks, or product names of the Licensor,
except as required for reasonable and customary use in describing the
origin of the Work and reproducing the content of the NOTICE file.
7. Disclaimer of Warranty. Unless required by applicable law or
agreed to in writing, Licensor provides the Work (and each
Contributor provides its Contributions) on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
implied, including, without limitation, any warranties or conditions
of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A
PARTICULAR PURPOSE. You are solely responsible for determining the
appropriateness of using or redistributing the Work and assume any
risks associated with Your exercise of permissions under this License.
8. Limitation of Liability. In no event and under no legal theory,
whether in tort (including negligence), contract, or otherwise,
unless required by applicable law (such as deliberate and grossly
negligent acts) or agreed to in writing, shall any Contributor be
liable to You for damages, including any direct, indirect, special,
incidental, or consequential damages of any character arising as a
result of this License or out of the use or inability to use the
Work (including but not limited to damages for loss of goodwill,
work stoppage, computer failure or malfunction, or any and all
other commercial damages or losses), even if such Contributor
has been advised of the possibility of such damages.
9. Accepting Warranty or Additional Liability. While redistributing
the Work or Derivative Works thereof, You may choose to offer,
and charge a fee for, acceptance of support, warranty, indemnity,
or other liability obligations and/or rights consistent with this
License. However, in accepting such obligations, You may act only
on Your own behalf and on Your sole responsibility, not on behalf
of any other Contributor, and only if You agree to indemnify,
defend, and hold each Contributor harmless for any liability
incurred by, or claims asserted against, such Contributor by reason
of your accepting any such warranty or additional liability.
END OF TERMS AND CONDITIONS
=========================================================================
This project contains annotations in the package org.apache.http.annotation
which are derived from JCIP-ANNOTATIONS
Copyright (c) 2005 Brian Goetz and Tim Peierls.
See http://www.jcip.net and the Creative Commons Attribution License
(http://creativecommons.org/licenses/by/2.5)
Full text: http://creativecommons.org/licenses/by/2.5/legalcode
License
THE WORK (AS DEFINED BELOW) IS PROVIDED UNDER THE TERMS OF THIS CREATIVE COMMONS PUBLIC LICENSE ("CCPL" OR "LICENSE"). THE WORK IS PROTECTED BY COPYRIGHT AND/OR OTHER APPLICABLE LAW. ANY USE OF THE WORK OTHER THAN AS AUTHORIZED UNDER THIS LICENSE OR COPYRIGHT LAW IS PROHIBITED.
BY EXERCISING ANY RIGHTS TO THE WORK PROVIDED HERE, YOU ACCEPT AND AGREE TO BE BOUND BY THE TERMS OF THIS LICENSE. THE LICENSOR GRANTS YOU THE RIGHTS CONTAINED HERE IN CONSIDERATION OF YOUR ACCEPTANCE OF SUCH TERMS AND CONDITIONS.
1. Definitions
"Collective Work" means a work, such as a periodical issue, anthology or encyclopedia, in which the Work in its entirety in unmodified form, along with a number of other contributions, constituting separate and independent works in themselves, are assembled into a collective whole. A work that constitutes a Collective Work will not be considered a Derivative Work (as defined below) for the purposes of this License.
"Derivative Work" means a work based upon the Work or upon the Work and other pre-existing works, such as a translation, musical arrangement, dramatization, fictionalization, motion picture version, sound recording, art reproduction, abridgment, condensation, or any other form in which the Work may be recast, transformed, or adapted, except that a work that constitutes a Collective Work will not be considered a Derivative Work for the purpose of this License. For the avoidance of doubt, where the Work is a musical composition or sound recording, the synchronization of the Work in timed-relation with a moving image ("synching") will be considered a Derivative Work for the purpose of this License.
"Licensor" means the individual or entity that offers the Work under the terms of this License.
"Original Author" means the individual or entity who created the Work.
"Work" means the copyrightable work of authorship offered under the terms of this License.
"You" means an individual or entity exercising rights under this License who has not previously violated the terms of this License with respect to the Work, or who has received express permission from the Licensor to exercise rights under this License despite a previous violation.
2. Fair Use Rights. Nothing in this license is intended to reduce, limit, or restrict any rights arising from fair use, first sale or other limitations on the exclusive rights of the copyright owner under copyright law or other applicable laws.
3. License Grant. Subject to the terms and conditions of this License, Licensor hereby grants You a worldwide, royalty-free, non-exclusive, perpetual (for the duration of the applicable copyright) license to exercise the rights in the Work as stated below:
to reproduce the Work, to incorporate the Work into one or more Collective Works, and to reproduce the Work as incorporated in the Collective Works;
to create and reproduce Derivative Works;
to distribute copies or phonorecords of, display publicly, perform publicly, and perform publicly by means of a digital audio transmission the Work including as incorporated in Collective Works;
to distribute copies or phonorecords of, display publicly, perform publicly, and perform publicly by means of a digital audio transmission Derivative Works.
For the avoidance of doubt, where the work is a musical composition:
Performance Royalties Under Blanket Licenses. Licensor waives the exclusive right to collect, whether individually or via a performance rights society (e.g. ASCAP, BMI, SESAC), royalties for the public performance or public digital performance (e.g. webcast) of the Work.
Mechanical Rights and Statutory Royalties. Licensor waives the exclusive right to collect, whether individually or via a music rights agency or designated agent (e.g. Harry Fox Agency), royalties for any phonorecord You create from the Work ("cover version") and distribute, subject to the compulsory license created by 17 USC Section 115 of the US Copyright Act (or the equivalent in other jurisdictions).
Webcasting Rights and Statutory Royalties. For the avoidance of doubt, where the Work is a sound recording, Licensor waives the exclusive right to collect, whether individually or via a performance-rights society (e.g. SoundExchange), royalties for the public digital performance (e.g. webcast) of the Work, subject to the compulsory license created by 17 USC Section 114 of the US Copyright Act (or the equivalent in other jurisdictions).
The above rights may be exercised in all media and formats whether now known or hereafter devised. The above rights include the right to make such modifications as are technically necessary to exercise the rights in other media and formats. All rights not expressly granted by Licensor are hereby reserved.
4. Restrictions.The license granted in Section 3 above is expressly made subject to and limited by the following restrictions:
You may distribute, publicly display, publicly perform, or publicly digitally perform the Work only under the terms of this License, and You must include a copy of, or the Uniform Resource Identifier for, this License with every copy or phonorecord of the Work You distribute, publicly display, publicly perform, or publicly digitally perform. You may not offer or impose any terms on the Work that alter or restrict the terms of this License or the recipients' exercise of the rights granted hereunder. You may not sublicense the Work. You must keep intact all notices that refer to this License and to the disclaimer of warranties. You may not distribute, publicly display, publicly perform, or publicly digitally perform the Work with any technological measures that control access or use of the Work in a manner inconsistent with the terms of this License Agreement. The above applies to the Work as incorporated in a Collective Work, but this does not require the Collective Work apart from the Work itself to be made subject to the terms of this License. If You create a Collective Work, upon notice from any Licensor You must, to the extent practicable, remove from the Collective Work any credit as required by clause 4(b), as requested. If You create a Derivative Work, upon notice from any Licensor You must, to the extent practicable, remove from the Derivative Work any credit as required by clause 4(b), as requested.
If you distribute, publicly display, publicly perform, or publicly digitally perform the Work or any Derivative Works or Collective Works, You must keep intact all copyright notices for the Work and provide, reasonable to the medium or means You are utilizing: (i) the name of the Original Author (or pseudonym, if applicable) if supplied, and/or (ii) if the Original Author and/or Licensor designate another party or parties (e.g. a sponsor institute, publishing entity, journal) for attribution in Licensor's copyright notice, terms of service or by other reasonable means, the name of such party or parties; the title of the Work if supplied; to the extent reasonably practicable, the Uniform Resource Identifier, if any, that Licensor specifies to be associated with the Work, unless such URI does not refer to the copyright notice or licensing information for the Work; and in the case of a Derivative Work, a credit identifying the use of the Work in the Derivative Work (e.g., "French translation of the Work by Original Author," or "Screenplay based on original Work by Original Author"). Such credit may be implemented in any reasonable manner; provided, however, that in the case of a Derivative Work or Collective Work, at a minimum such credit will appear where any other comparable authorship credit appears and in a manner at least as prominent as such other comparable authorship credit.
5. Representations, Warranties and Disclaimer
UNLESS OTHERWISE MUTUALLY AGREED TO BY THE PARTIES IN WRITING, LICENSOR OFFERS THE WORK AS-IS AND MAKES NO REPRESENTATIONS OR WARRANTIES OF ANY KIND CONCERNING THE WORK, EXPRESS, IMPLIED, STATUTORY OR OTHERWISE, INCLUDING, WITHOUT LIMITATION, WARRANTIES OF TITLE, MERCHANTIBILITY, FITNESS FOR A PARTICULAR PURPOSE, NONINFRINGEMENT, OR THE ABSENCE OF LATENT OR OTHER DEFECTS, ACCURACY, OR THE PRESENCE OF ABSENCE OF ERRORS, WHETHER OR NOT DISCOVERABLE. SOME JURISDICTIONS DO NOT ALLOW THE EXCLUSION OF IMPLIED WARRANTIES, SO SUCH EXCLUSION MAY NOT APPLY TO YOU.
6. Limitation on Liability. EXCEPT TO THE EXTENT REQUIRED BY APPLICABLE LAW, IN NO EVENT WILL LICENSOR BE LIABLE TO YOU ON ANY LEGAL THEORY FOR ANY SPECIAL, INCIDENTAL, CONSEQUENTIAL, PUNITIVE OR EXEMPLARY DAMAGES ARISING OUT OF THIS LICENSE OR THE USE OF THE WORK, EVEN IF LICENSOR HAS BEEN ADVISED OF THE POSSIBILITY OF SUCH DAMAGES.
7. Termination
This License and the rights granted hereunder will terminate automatically upon any breach by You of the terms of this License. Individuals or entities who have received Derivative Works or Collective Works from You under this License, however, will not have their licenses terminated provided such individuals or entities remain in full compliance with those licenses. Sections 1, 2, 5, 6, 7, and 8 will survive any termination of this License.
Subject to the above terms and conditions, the license granted here is perpetual (for the duration of the applicable copyright in the Work). Notwithstanding the above, Licensor reserves the right to release the Work under different license terms or to stop distributing the Work at any time; provided, however that any such election will not serve to withdraw this License (or any other license that has been, or is required to be, granted under the terms of this License), and this License will continue in full force and effect unless terminated as stated above.
8. Miscellaneous
Each time You distribute or publicly digitally perform the Work or a Collective Work, the Licensor offers to the recipient a license to the Work on the same terms and conditions as the license granted to You under this License.
Each time You distribute or publicly digitally perform a Derivative Work, Licensor offers to the recipient a license to the original Work on the same terms and conditions as the license granted to You under this License.
If any provision of this License is invalid or unenforceable under applicable law, it shall not affect the validity or enforceability of the remainder of the terms of this License, and without further action by the parties to this agreement, such provision shall be reformed to the minimum extent necessary to make such provision valid and enforceable.
No term or provision of this License shall be deemed waived and no breach consented to unless such waiver or consent shall be in writing and signed by the party to be charged with such waiver or consent.
This License constitutes the entire agreement between the parties with respect to the Work licensed here. There are no understandings, agreements or representations with respect to the Work not specified here. Licensor shall not be bound by any additional provisions that may appear in any communication from You. This License may not be modified without the mutual written agreement of the Licensor and You.

View File

@ -1,8 +0,0 @@
Apache HttpComponents HttpClient for Android
Copyright 2005-2014 The Apache Software Foundation
This product includes software developed at
The Apache Software Foundation (http://www.apache.org/).
This project contains annotations derived from JCIP-ANNOTATIONS
Copyright (c) 2005 Brian Goetz and Tim Peierls. See http://www.jcip.net

View File

@ -1,46 +0,0 @@
This project represents an effort to provide an implementation of Apache HttpClient, which can be
deployed on Google Android in parallel to the outdated version shipped with platform while
remaining partially API compatible with Apache HttpClient 4.3.
Background
----------
Google Android 1.0 was released with a pre-BETA snapshot of Apache HttpClient 4.0. To coincide with
the first Android release Apache HttpClient 4.0 APIs had to be frozen prematurely, while many of
interfaces and internal structures were still not fully worked out. As Apache HttpClient 4.0 was
maturing the project was expecting Google to incorporate the latest code improvements into their
code tree. Unfortunately it did not happen. Version of Apache HttpClient shipped with Android has
effectively became a fork. Eventually Google decided to discontinue further development of their
fork while refusing to upgrade to the stock version of Apache HttpClient citing compatibility
concerns as a reason for such decision. As a result those Android developers who would like to
continue using Apache HttpClient APIs on Android cannot take advantage of newer features, performance
improvements and bug fixes.
Apache HttpClient 4.3 port for Android is intended to remedy the situation by providing
official releases compatible with Google Android.
Differences with the stock version of Apache HttpClient
----------
(1) Compiled against HttpClient 4.0 APIs.
(2) Commons Logging replaced with Android Logging.
(3) Base64 implementation from Commons Codec replaced with Android Base64.
(4) Android default SSLSocketFactory used by for SSL/TLS connections.
Compatibility notes
----------
(1) HttpClient port for Android is compiled against the official Android SDK and is expected
to be fully compatible with any code consuming HttpClient services through its interface
(HttpClient) rather than the default implementation (DefaultHttpClient).
(2) Code compiled against stock versions of Apache HttpClient 4.3 is not fully compatible with
the HttpClient port for Android. Some of the implementation classes had to be copied (or shaded)
with different names in order to avoid conflicts with the older versions of the same classes
included in the Android runtime. One can increase compatibility with the stock version of
HttpClient by avoiding 'org.apache.http.**.*HC4' classes.

View File

@ -1,38 +0,0 @@
Release 4.3.5.1
-------------------
This release fixes a number of issues related to Android specific modifications made to
the original HttpClient 4.3.5 code used as a base for the Android port.
Please note that as of this release HttpClient disables all versions of SSL (including SSLv3)
in favor of the TLS protocol by default. Those users who wish to continue using SSLv3 need
to explicitly enable support for it.
Users of all versions of Apache HttpClient 4.3 port for Android are advised to upgrade.
Changelog
-------------------
* SSLv3 protocol is disabled by default
Contributed by Oleg Kalnichevski <olegk at apache.org>
* [HTTPCLIENT-1597] Hostname verifiers incorrectly reject certificates with empty attributes
in the certificate subject
Contributed by Oleg Kalnichevski <olegk at apache.org>
* [HTTPCLIENT-1591] Invoke Android specific SNI method via reflection
Contributed by Oleg Kalnichevski <olegk at apache.org>
* [HTTPCLIENT-1566] Fixed broken Base64 encoding in BasicScheme
Contributed by Oleg Kalnichevski <olegk at apache.org>
* [HTTPCLIENT-1554] RequestConfig has no effect when using Android HttpRequest classes.
Contributed by Oleg Kalnichevski <olegk at apache.org>
* [HTTPCLIENT-1555] SSL handshake timeout is always zero (infinite).
Contributed by Oleg Kalnichevski <olegk at apache.org>
* [HTTPCLIENT-1553] Fixed IllegalArgumentException in HttpClientBuilder.build() if system
properties are not used.
Contributed by Oleg Kalnichevski <olegk at apache.org>

View File

@ -1,295 +0,0 @@
/*
* ====================================================================
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you under the Apache License, Version 2.0 (the
* "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
* KIND, either express or implied. See the License for the
* specific language governing permissions and limitations
* under the License.
* ====================================================================
*
* This software consists of voluntary contributions made by many
* individuals on behalf of the Apache Software Foundation. For more
* information on the Apache Software Foundation, please see
* <http://www.apache.org/>.
*
*/
buildscript {
repositories {
mavenCentral()
}
dependencies {
classpath 'com.android.tools.build:gradle:1.0.1'
}
}
apply plugin: 'com.android.library'
apply plugin: 'maven'
apply plugin: 'signing'
repositories {
mavenCentral()
}
group = 'org.apache.httpcomponents'
version = HC_VER
ext.isRelease = !version.endsWith('-SNAPSHOT')
ext.inceptionYear = '1999'
android {
// SDK versions and compileOptions adapted to DAVdroid needs
compileSdkVersion 22
buildToolsVersion '22.0.1'
defaultConfig {
minSdkVersion 8
targetSdkVersion 22
}
/*compileOptions {
sourceCompatibility JavaVersion.VERSION_1_5
targetCompatibility JavaVersion.VERSION_1_5
}*/
}
configurations {
dist
}
signing {
required { isRelease }
}
ext.sharedManifest = manifest {
attributes (
'Specification-Title': "HttpComponents HttpClient for Android",
'Specification-Version': "$version",
'Specification-Vendor': "The Apache Software Foundation",
'Implementation-Title': "HttpComponents HttpClient for Android",
'Implementation-Version': "$version",
'Implementation-Vendor': "The Apache Software Foundation",
'Implementation-Vendor-Id': "org.apache",
'url': 'http://hc.apache.org/httpcomponents-client'
)
}
android.libraryVariants.all { variant ->
def name = variant.buildType.name
if (name == 'release') {
task createAndroidJar(type: Jar) {
dependsOn variant.javaCompile
from variant.javaCompile.destinationDir
from 'NOTICE.txt'
from 'LICENSE.txt'
rename '(NOTICE|LICENSE).txt', 'META-INF/$1'
manifest {
from sharedManifest
}
}
task createAndroidSrcJar(type: Jar) {
dependsOn variant.javaCompile
from variant.javaCompile.source
from 'NOTICE.txt'
from 'LICENSE.txt'
rename '(NOTICE|LICENSE).txt', 'META-INF/$1'
classifier = 'sources'
manifest {
from sharedManifest
}
}
task createAndroidJavadoc(type: Javadoc) {
dependsOn variant.javaCompile
source = variant.javaCompile.source
classpath = files(android.plugin.bootClasspath, variant.javaCompile.classpath.files)
title "Apache HttpClient for Android $HC_VER API"
configure (options) {
docTitle "Apache HttpClient for Android $HC_VER API"
bottom "Copyright &copy; ${inceptionYear}-${Calendar.instance.get(Calendar.YEAR)} " +
"<a href=\"http://www.apache.org/\">The Apache Software Foundation</a>. " +
"All rights reserved."
}
}
task createAndroidJavadocJar(type: Jar) {
dependsOn createAndroidJavadoc
from createAndroidJavadoc.destinationDir
from 'NOTICE.txt'
from 'LICENSE.txt'
rename '(NOTICE|LICENSE).txt', 'META-INF/$1'
classifier = 'javadoc'
manifest {
from sharedManifest
}
}
artifacts {
dist createAndroidJar
dist createAndroidSrcJar
dist createAndroidJavadocJar
}
signing {
sign createAndroidJar
sign createAndroidSrcJar
sign createAndroidJavadocJar
}
artifacts {
tasks.withType(Sign) { Sign task ->
task.signatures.each { PublishArtifact artifact ->
dist artifact
}
}
}
}
}
// Deployment tasks
def askPassphrase = {
Console console = System.console()
if (console) {
String password = project.ext.has('signing.password') ? project.ext.'signing.password' : null
String keyId = project.ext.has('signing.keyId') ? project.ext.'signing.keyId' : null
if (keyId && !password) {
char[] raw = console.readPassword("\n> Please provide password for PGP key ${keyId}: ")
project.ext.'signing.password' = new String(raw)
}
}
}
def askCredentials(MavenDeployer mavenDeployer) {
Console console = System.console()
if (console) {
URL url = new URL(mavenDeployer.repository.url)
def auth = mavenDeployer.repository.authentication
if (auth) {
if (!auth.userName || auth.userName == '') {
String username = console.readLine("\n> Please enter user name for repository '${url}': ")
auth.userName = username
}
if (!auth.password || auth.password == '') {
char[] raw = console.readPassword("\n> Please enter password for repository '${url}': ")
auth.password = new String(raw)
}
}
}
}
project.ext.archiveSources = copySpec {
from (project.projectDir) {
include 'src/**'
include '*.txt'
include 'build.gradle'
include 'settings.gradle'
include 'gradle.properties'
}
}
task archiveSrcWin(type: Zip) {
with archiveSources
filter(['eol': org.apache.tools.ant.filters.FixCrLfFilter.CrLf.newInstance('crlf')],
org.apache.tools.ant.filters.FixCrLfFilter)
into "httpcomponents-client-android-$project.version"
classifier = 'src'
baseName = 'httpcomponents-client-android'
version = project.version
}
task archiveSrcUnix(type: Tar) {
with archiveSources
into "httpcomponents-client-android-$project.version"
filter(['eol': org.apache.tools.ant.filters.FixCrLfFilter.CrLf.newInstance('lf')],
org.apache.tools.ant.filters.FixCrLfFilter)
classifier = 'src'
baseName = 'httpcomponents-client-android'
version = project.version
extension = 'tar.gz'
compression = Compression.GZIP
}
task uploadDist(type: Upload) {
configuration = configurations.dist
repositories {
mavenDeployer {
def creds = [
userName: project.ext.has('asf.username') ? project.ext.'asf.username' : null,
password: project.ext.has('asf.password') ? project.ext.'asf.password' : null ]
if (System.properties['localRepo']) {
repository(url: "file:${buildDir.absolutePath}/repo")
} else {
if (version.endsWith('-SNAPSHOT')) {
repository(url: ASF_SNAPSHOT_REPO) {
authentication(creds)
}
} else {
repository(url: ASF_NEXUS_STAGE) {
authentication(creds)
}
}
}
pom.project {
name 'HttpComponents Client for Android'
url 'http://hc.apache.org/httpcomponents-client/'
organization {
name 'The Apache Software Foundation'
url 'http://www.apache.org/'
}
licenses {
license {
name 'Apache License, Version 2.0'
url 'LICENSE.txt'
distribution 'repo'
}
}
issueManagement {
system 'Jira'
url 'http://issues.apache.org/jira/browse/HTTPCLIENT'
}
}
if (isRelease) {
beforeDeployment { MavenDeployment deployment ->
askPassphrase()
signing.signPom(deployment)
}
}
}
}
}
gradle.taskGraph.whenReady { TaskExecutionGraph taskGraph ->
taskGraph.allTasks.findAll { Task task ->
task instanceof Upload }.each { Upload task ->
task.doFirst {
task.repositories.each { MavenDeployer mavenDeployer ->
askCredentials(mavenDeployer)
}
}
}
taskGraph.allTasks.findAll { Task task ->
task instanceof Sign }.each { Sign task ->
task.doFirst { askPassphrase() }
}
}

View File

@ -1,3 +0,0 @@
HC_VER=4.3.5.2-SNAPSHOT
ASF_SNAPSHOT_REPO=https://repository.apache.org/content/repositories/snapshots
ASF_NEXUS_STAGE=https://repository.apache.org/service/local/staging/deploy/maven2

View File

@ -1 +0,0 @@
rootProject.name = 'httpclient-android'

View File

@ -1,30 +0,0 @@
<!--
====================================================================
Licensed to the Apache Software Foundation (ASF) under one
or more contributor license agreements. See the NOTICE file
distributed with this work for additional information
regarding copyright ownership. The ASF licenses this file
to you under the Apache License, Version 2.0 (the
"License"); you may not use this file except in compliance
with the License. You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing,
software distributed under the License is distributed on an
"AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
KIND, either express or implied. See the License for the
specific language governing permissions and limitations
under the License.
====================================================================
This software consists of voluntary contributions made by many
individuals on behalf of the Apache Software Foundation. For more
information on the Apache Software Foundation, please see
<http://www.apache.org />.
-->
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
package="org.apache.http"
android:versionCode="1"
android:versionName="1.0">
</manifest>

View File

@ -1,51 +0,0 @@
/*
* ====================================================================
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you under the Apache License, Version 2.0 (the
* "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
* KIND, either express or implied. See the License for the
* specific language governing permissions and limitations
* under the License.
* ====================================================================
*
* This software consists of voluntary contributions made by many
* individuals on behalf of the Apache Software Foundation. For more
* information on the Apache Software Foundation, please see
* <http://www.apache.org/>.
*
*/
package org.apache.http;
import java.nio.charset.Charset;
/**
* Commons constants.
*
* @since 4.2
*/
public final class Consts {
public static final int CR = 13; // <US-ASCII CR, carriage return (13)>
public static final int LF = 10; // <US-ASCII LF, linefeed (10)>
public static final int SP = 32; // <US-ASCII SP, space (32)>
public static final int HT = 9; // <US-ASCII HT, horizontal-tab (9)>
public static final Charset UTF_8 = Charset.forName("UTF-8");
public static final Charset ASCII = Charset.forName("US-ASCII");
public static final Charset ISO_8859_1 = Charset.forName("ISO-8859-1");
private Consts() {
}
}

View File

@ -1,50 +0,0 @@
/*
* ====================================================================
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you under the Apache License, Version 2.0 (the
* "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
* KIND, either express or implied. See the License for the
* specific language governing permissions and limitations
* under the License.
* ====================================================================
*
* This software consists of voluntary contributions made by many
* individuals on behalf of the Apache Software Foundation. For more
* information on the Apache Software Foundation, please see
* <http://www.apache.org/>.
*
*/
package org.apache.http;
import java.io.IOException;
/**
* Signals that HTTP entity content is too long.
*
* @since 4.2
*/
public class ContentTooLongException extends IOException {
private static final long serialVersionUID = -924287689552495383L;
/**
* Creates a new ContentTooLongException with the specified detail message.
*
* @param message exception message
*/
public ContentTooLongException(final String message) {
super(message);
}
}

View File

@ -1,42 +0,0 @@
/*
* ====================================================================
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you under the Apache License, Version 2.0 (the
* "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
* KIND, either express or implied. See the License for the
* specific language governing permissions and limitations
* under the License.
* ====================================================================
*
* This software consists of voluntary contributions made by many
* individuals on behalf of the Apache Software Foundation. For more
* information on the Apache Software Foundation, please see
* <http://www.apache.org/>.
*
*/
package org.apache.http;
import java.io.IOException;
import java.net.Socket;
/**
* Factory for {@link HttpConnection} instances.
*
* @since 4.3
*/
public interface HttpConnectionFactory<T extends HttpConnection> {
T createConnection(Socket socket) throws IOException;
}

View File

@ -1,206 +0,0 @@
/*
* ====================================================================
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you under the Apache License, Version 2.0 (the
* "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
* KIND, either express or implied. See the License for the
* specific language governing permissions and limitations
* under the License.
* ====================================================================
*
* This software consists of voluntary contributions made by many
* individuals on behalf of the Apache Software Foundation. For more
* information on the Apache Software Foundation, please see
* <http://www.apache.org/>.
*
*/
package org.apache.http;
/**
* Constants enumerating the HTTP headers. All headers defined in RFC1945 (HTTP/1.0), RFC2616 (HTTP/1.1), and RFC2518
* (WebDAV) are listed.
*
* @since 4.1
*/
public final class HttpHeaders {
private HttpHeaders() {
}
/** RFC 2616 (HTTP/1.1) Section 14.1 */
public static final String ACCEPT = "Accept";
/** RFC 2616 (HTTP/1.1) Section 14.2 */
public static final String ACCEPT_CHARSET = "Accept-Charset";
/** RFC 2616 (HTTP/1.1) Section 14.3 */
public static final String ACCEPT_ENCODING = "Accept-Encoding";
/** RFC 2616 (HTTP/1.1) Section 14.4 */
public static final String ACCEPT_LANGUAGE = "Accept-Language";
/** RFC 2616 (HTTP/1.1) Section 14.5 */
public static final String ACCEPT_RANGES = "Accept-Ranges";
/** RFC 2616 (HTTP/1.1) Section 14.6 */
public static final String AGE = "Age";
/** RFC 1945 (HTTP/1.0) Section 10.1, RFC 2616 (HTTP/1.1) Section 14.7 */
public static final String ALLOW = "Allow";
/** RFC 1945 (HTTP/1.0) Section 10.2, RFC 2616 (HTTP/1.1) Section 14.8 */
public static final String AUTHORIZATION = "Authorization";
/** RFC 2616 (HTTP/1.1) Section 14.9 */
public static final String CACHE_CONTROL = "Cache-Control";
/** RFC 2616 (HTTP/1.1) Section 14.10 */
public static final String CONNECTION = "Connection";
/** RFC 1945 (HTTP/1.0) Section 10.3, RFC 2616 (HTTP/1.1) Section 14.11 */
public static final String CONTENT_ENCODING = "Content-Encoding";
/** RFC 2616 (HTTP/1.1) Section 14.12 */
public static final String CONTENT_LANGUAGE = "Content-Language";
/** RFC 1945 (HTTP/1.0) Section 10.4, RFC 2616 (HTTP/1.1) Section 14.13 */
public static final String CONTENT_LENGTH = "Content-Length";
/** RFC 2616 (HTTP/1.1) Section 14.14 */
public static final String CONTENT_LOCATION = "Content-Location";
/** RFC 2616 (HTTP/1.1) Section 14.15 */
public static final String CONTENT_MD5 = "Content-MD5";
/** RFC 2616 (HTTP/1.1) Section 14.16 */
public static final String CONTENT_RANGE = "Content-Range";
/** RFC 1945 (HTTP/1.0) Section 10.5, RFC 2616 (HTTP/1.1) Section 14.17 */
public static final String CONTENT_TYPE = "Content-Type";
/** RFC 1945 (HTTP/1.0) Section 10.6, RFC 2616 (HTTP/1.1) Section 14.18 */
public static final String DATE = "Date";
/** RFC 2518 (WevDAV) Section 9.1 */
public static final String DAV = "Dav";
/** RFC 2518 (WevDAV) Section 9.2 */
public static final String DEPTH = "Depth";
/** RFC 2518 (WevDAV) Section 9.3 */
public static final String DESTINATION = "Destination";
/** RFC 2616 (HTTP/1.1) Section 14.19 */
public static final String ETAG = "ETag";
/** RFC 2616 (HTTP/1.1) Section 14.20 */
public static final String EXPECT = "Expect";
/** RFC 1945 (HTTP/1.0) Section 10.7, RFC 2616 (HTTP/1.1) Section 14.21 */
public static final String EXPIRES = "Expires";
/** RFC 1945 (HTTP/1.0) Section 10.8, RFC 2616 (HTTP/1.1) Section 14.22 */
public static final String FROM = "From";
/** RFC 2616 (HTTP/1.1) Section 14.23 */
public static final String HOST = "Host";
/** RFC 2518 (WevDAV) Section 9.4 */
public static final String IF = "If";
/** RFC 2616 (HTTP/1.1) Section 14.24 */
public static final String IF_MATCH = "If-Match";
/** RFC 1945 (HTTP/1.0) Section 10.9, RFC 2616 (HTTP/1.1) Section 14.25 */
public static final String IF_MODIFIED_SINCE = "If-Modified-Since";
/** RFC 2616 (HTTP/1.1) Section 14.26 */
public static final String IF_NONE_MATCH = "If-None-Match";
/** RFC 2616 (HTTP/1.1) Section 14.27 */
public static final String IF_RANGE = "If-Range";
/** RFC 2616 (HTTP/1.1) Section 14.28 */
public static final String IF_UNMODIFIED_SINCE = "If-Unmodified-Since";
/** RFC 1945 (HTTP/1.0) Section 10.10, RFC 2616 (HTTP/1.1) Section 14.29 */
public static final String LAST_MODIFIED = "Last-Modified";
/** RFC 1945 (HTTP/1.0) Section 10.11, RFC 2616 (HTTP/1.1) Section 14.30 */
public static final String LOCATION = "Location";
/** RFC 2518 (WevDAV) Section 9.5 */
public static final String LOCK_TOKEN = "Lock-Token";
/** RFC 2616 (HTTP/1.1) Section 14.31 */
public static final String MAX_FORWARDS = "Max-Forwards";
/** RFC 2518 (WevDAV) Section 9.6 */
public static final String OVERWRITE = "Overwrite";
/** RFC 1945 (HTTP/1.0) Section 10.12, RFC 2616 (HTTP/1.1) Section 14.32 */
public static final String PRAGMA = "Pragma";
/** RFC 2616 (HTTP/1.1) Section 14.33 */
public static final String PROXY_AUTHENTICATE = "Proxy-Authenticate";
/** RFC 2616 (HTTP/1.1) Section 14.34 */
public static final String PROXY_AUTHORIZATION = "Proxy-Authorization";
/** RFC 2616 (HTTP/1.1) Section 14.35 */
public static final String RANGE = "Range";
/** RFC 1945 (HTTP/1.0) Section 10.13, RFC 2616 (HTTP/1.1) Section 14.36 */
public static final String REFERER = "Referer";
/** RFC 2616 (HTTP/1.1) Section 14.37 */
public static final String RETRY_AFTER = "Retry-After";
/** RFC 1945 (HTTP/1.0) Section 10.14, RFC 2616 (HTTP/1.1) Section 14.38 */
public static final String SERVER = "Server";
/** RFC 2518 (WevDAV) Section 9.7 */
public static final String STATUS_URI = "Status-URI";
/** RFC 2616 (HTTP/1.1) Section 14.39 */
public static final String TE = "TE";
/** RFC 2518 (WevDAV) Section 9.8 */
public static final String TIMEOUT = "Timeout";
/** RFC 2616 (HTTP/1.1) Section 14.40 */
public static final String TRAILER = "Trailer";
/** RFC 2616 (HTTP/1.1) Section 14.41 */
public static final String TRANSFER_ENCODING = "Transfer-Encoding";
/** RFC 2616 (HTTP/1.1) Section 14.42 */
public static final String UPGRADE = "Upgrade";
/** RFC 1945 (HTTP/1.0) Section 10.15, RFC 2616 (HTTP/1.1) Section 14.43 */
public static final String USER_AGENT = "User-Agent";
/** RFC 2616 (HTTP/1.1) Section 14.44 */
public static final String VARY = "Vary";
/** RFC 2616 (HTTP/1.1) Section 14.45 */
public static final String VIA = "Via";
/** RFC 2616 (HTTP/1.1) Section 14.46 */
public static final String WARNING = "Warning";
/** RFC 1945 (HTTP/1.0) Section 10.16, RFC 2616 (HTTP/1.1) Section 14.47 */
public static final String WWW_AUTHENTICATE = "WWW-Authenticate";
}

View File

@ -1,50 +0,0 @@
/*
* ====================================================================
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you under the Apache License, Version 2.0 (the
* "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
* KIND, either express or implied. See the License for the
* specific language governing permissions and limitations
* under the License.
* ====================================================================
*
* This software consists of voluntary contributions made by many
* individuals on behalf of the Apache Software Foundation. For more
* information on the Apache Software Foundation, please see
* <http://www.apache.org/>.
*
*/
package org.apache.http;
import java.io.IOException;
/**
* Signals a message constraint violation.
*
* @since 4.3
*/
public class MessageConstraintException extends IOException {
private static final long serialVersionUID = 6077207720446368695L;
/**
* Creates a TruncatedChunkException with the specified detail message.
*
* @param message The exception detail message
*/
public MessageConstraintException(final String message) {
super(message);
}
}

View File

@ -1,48 +0,0 @@
/*
* ====================================================================
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you under the Apache License, Version 2.0 (the
* "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
* KIND, either express or implied. See the License for the
* specific language governing permissions and limitations
* under the License.
* ====================================================================
*
* This software consists of voluntary contributions made by many
* individuals on behalf of the Apache Software Foundation. For more
* information on the Apache Software Foundation, please see
* <http://www.apache.org/>.
*
*/
package org.apache.http;
/**
* Signals a truncated chunk in a chunked stream.
*
* @since 4.1
*/
public class TruncatedChunkException extends MalformedChunkCodingException {
private static final long serialVersionUID = -23506263930279460L;
/**
* Creates a TruncatedChunkException with the specified detail message.
*
* @param message The exception detail message
*/
public TruncatedChunkException(final String message) {
super(message);
}
}

View File

@ -1,76 +0,0 @@
/*
* ====================================================================
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you under the Apache License, Version 2.0 (the
* "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
* KIND, either express or implied. See the License for the
* specific language governing permissions and limitations
* under the License.
* ====================================================================
*
* This software consists of voluntary contributions made by many
* individuals on behalf of the Apache Software Foundation. For more
* information on the Apache Software Foundation, please see
* <http://www.apache.org/>.
*
*/
package org.apache.http.annotation;
import java.lang.annotation.Documented;
import java.lang.annotation.ElementType;
import java.lang.annotation.Retention;
import java.lang.annotation.RetentionPolicy;
import java.lang.annotation.Target;
/**
* The field or method to which this annotation is applied can only be accessed
* when holding a particular lock, which may be a built-in (synchronization) lock,
* or may be an explicit java.util.concurrent.Lock.
*
* The argument determines which lock guards the annotated field or method:
* <ul>
* <li>
* <code>this</code> : The intrinsic lock of the object in whose class the field is defined.
* </li>
* <li>
* <code>class-name.this</code> : For inner classes, it may be necessary to disambiguate 'this';
* the <em>class-name.this</em> designation allows you to specify which 'this' reference is intended
* </li>
* <li>
* <code>itself</code> : For reference fields only; the object to which the field refers.
* </li>
* <li>
* <code>field-name</code> : The lock object is referenced by the (instance or static) field
* specified by <em>field-name</em>.
* </li>
* <li>
* <code>class-name.field-name</code> : The lock object is reference by the static field specified
* by <em>class-name.field-name</em>.
* </li>
* <li>
* <code>method-name()</code> : The lock object is returned by calling the named nil-ary method.
* </li>
* <li>
* <code>class-name.class</code> : The Class object for the specified class should be used as the lock object.
* </li>
* <p>
* Based on code developed by Brian Goetz and Tim Peierls and concepts
* published in 'Java Concurrency in Practice' by Brian Goetz, Tim Peierls,
* Joshua Bloch, Joseph Bowbeer, David Holmes and Doug Lea.
*/
@Documented
@Target({ElementType.FIELD, ElementType.METHOD})
@Retention(RetentionPolicy.CLASS) // The original version used RUNTIME
public @interface GuardedBy {
String value();
}

View File

@ -1,59 +0,0 @@
/*
* ====================================================================
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you under the Apache License, Version 2.0 (the
* "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
* KIND, either express or implied. See the License for the
* specific language governing permissions and limitations
* under the License.
* ====================================================================
*
* This software consists of voluntary contributions made by many
* individuals on behalf of the Apache Software Foundation. For more
* information on the Apache Software Foundation, please see
* <http://www.apache.org/>.
*
*/
package org.apache.http.annotation;
import java.lang.annotation.Documented;
import java.lang.annotation.ElementType;
import java.lang.annotation.Retention;
import java.lang.annotation.RetentionPolicy;
import java.lang.annotation.Target;
/**
* The class to which this annotation is applied is immutable. This means that
* its state cannot be seen to change by callers, which implies that
* <ul>
* <li> all public fields are final, </li>
* <li> all public final reference fields refer to other immutable objects, and </li>
* <li> constructors and methods do not publish references to any internal state
* which is potentially mutable by the implementation. </li>
* </ul>
* Immutable objects may still have internal mutable state for purposes of performance
* optimization; some state variables may be lazily computed, so long as they are computed
* from immutable state and that callers cannot tell the difference.
* <p>
* Immutable objects are inherently thread-safe; they may be passed between threads or
* published without synchronization.
* <p>
* Based on code developed by Brian Goetz and Tim Peierls and concepts
* published in 'Java Concurrency in Practice' by Brian Goetz, Tim Peierls,
* Joshua Bloch, Joseph Bowbeer, David Holmes and Doug Lea.
*/
@Documented
@Target(ElementType.TYPE)
@Retention(RetentionPolicy.CLASS) // The original version used RUNTIME
public @interface Immutable {
}

View File

@ -1,50 +0,0 @@
/*
* ====================================================================
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you under the Apache License, Version 2.0 (the
* "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
* KIND, either express or implied. See the License for the
* specific language governing permissions and limitations
* under the License.
* ====================================================================
*
* This software consists of voluntary contributions made by many
* individuals on behalf of the Apache Software Foundation. For more
* information on the Apache Software Foundation, please see
* <http://www.apache.org/>.
*
*/
package org.apache.http.annotation;
import java.lang.annotation.Documented;
import java.lang.annotation.ElementType;
import java.lang.annotation.Retention;
import java.lang.annotation.RetentionPolicy;
import java.lang.annotation.Target;
/**
* The class to which this annotation is applied is not thread-safe.
* This annotation primarily exists for clarifying the non-thread-safety of a class
* that might otherwise be assumed to be thread-safe, despite the fact that it is a bad
* idea to assume a class is thread-safe without good reason.
* @see ThreadSafe
* <p>
* Based on code developed by Brian Goetz and Tim Peierls and concepts
* published in 'Java Concurrency in Practice' by Brian Goetz, Tim Peierls,
* Joshua Bloch, Joseph Bowbeer, David Holmes and Doug Lea.
*/
@Documented
@Target(ElementType.TYPE)
@Retention(RetentionPolicy.CLASS) // The original version used RUNTIME
public @interface NotThreadSafe {
}

View File

@ -1,51 +0,0 @@
/*
* ====================================================================
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you under the Apache License, Version 2.0 (the
* "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
* KIND, either express or implied. See the License for the
* specific language governing permissions and limitations
* under the License.
* ====================================================================
*
* This software consists of voluntary contributions made by many
* individuals on behalf of the Apache Software Foundation. For more
* information on the Apache Software Foundation, please see
* <http://www.apache.org/>.
*
*/
package org.apache.http.annotation;
import java.lang.annotation.Documented;
import java.lang.annotation.ElementType;
import java.lang.annotation.Retention;
import java.lang.annotation.RetentionPolicy;
import java.lang.annotation.Target;
/**
* The class to which this annotation is applied is thread-safe. This means that
* no sequences of accesses (reads and writes to public fields, calls to public methods)
* may put the object into an invalid state, regardless of the interleaving of those actions
* by the runtime, and without requiring any additional synchronization or coordination on the
* part of the caller.
* @see NotThreadSafe
* <p>
* Based on code developed by Brian Goetz and Tim Peierls and concepts
* published in 'Java Concurrency in Practice' by Brian Goetz, Tim Peierls,
* Joshua Bloch, Joseph Bowbeer, David Holmes and Doug Lea.
*/
@Documented
@Target(ElementType.TYPE)
@Retention(RetentionPolicy.CLASS) // The original version used RUNTIME
public @interface ThreadSafe {
}

View File

@ -1,34 +0,0 @@
/*
* ====================================================================
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you under the Apache License, Version 2.0 (the
* "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
* KIND, either express or implied. See the License for the
* specific language governing permissions and limitations
* under the License.
* ====================================================================
*
* This software consists of voluntary contributions made by many
* individuals on behalf of the Apache Software Foundation. For more
* information on the Apache Software Foundation, please see
* <http://www.apache.org/>.
*
*/
/**
* Thread-safety annotations based on JCIP-ANNOTATIONS
* <br/>
* Copyright (c) 2005 Brian Goetz and Tim Peierls.
* See http://www.jcip.net
*/
package org.apache.http.annotation;

View File

@ -1,63 +0,0 @@
/*
* ====================================================================
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you under the Apache License, Version 2.0 (the
* "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
* KIND, either express or implied. See the License for the
* specific language governing permissions and limitations
* under the License.
* ====================================================================
*
* This software consists of voluntary contributions made by many
* individuals on behalf of the Apache Software Foundation. For more
* information on the Apache Software Foundation, please see
* <http://www.apache.org/>.
*
*/
package org.apache.http.auth;
import org.apache.http.annotation.Immutable;
import org.apache.http.util.Args;
/**
* @since 4.2
*/
@Immutable
public final class AuthOption {
private final AuthScheme authScheme;
private final Credentials creds;
public AuthOption(final AuthScheme authScheme, final Credentials creds) {
super();
Args.notNull(authScheme, "Auth scheme");
Args.notNull(creds, "User credentials");
this.authScheme = authScheme;
this.creds = creds;
}
public AuthScheme getAuthScheme() {
return this.authScheme;
}
public Credentials getCredentials() {
return this.creds;
}
@Override
public String toString() {
return this.authScheme.toString();
}
}

View File

@ -1,33 +0,0 @@
/*
* ====================================================================
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you under the Apache License, Version 2.0 (the
* "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
* KIND, either express or implied. See the License for the
* specific language governing permissions and limitations
* under the License.
* ====================================================================
*
* This software consists of voluntary contributions made by many
* individuals on behalf of the Apache Software Foundation. For more
* information on the Apache Software Foundation, please see
* <http://www.apache.org/>.
*
*/
package org.apache.http.auth;
public enum AuthProtocolState {
UNCHALLENGED, CHALLENGED, HANDSHAKE, FAILURE, SUCCESS
}

View File

@ -1,46 +0,0 @@
/*
* ====================================================================
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you under the Apache License, Version 2.0 (the
* "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
* KIND, either express or implied. See the License for the
* specific language governing permissions and limitations
* under the License.
* ====================================================================
*
* This software consists of voluntary contributions made by many
* individuals on behalf of the Apache Software Foundation. For more
* information on the Apache Software Foundation, please see
* <http://www.apache.org/>.
*
*/
package org.apache.http.auth;
import org.apache.http.protocol.HttpContext;
/**
* Factory for {@link AuthScheme} implementations.
*
* @since 4.3
*/
public interface AuthSchemeProvider {
/**
* Creates an instance of {@link AuthScheme}.
*
* @return auth scheme.
*/
AuthScheme create(HttpContext context);
}

View File

@ -1,235 +0,0 @@
/*
* ====================================================================
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you under the Apache License, Version 2.0 (the
* "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
* KIND, either express or implied. See the License for the
* specific language governing permissions and limitations
* under the License.
* ====================================================================
*
* This software consists of voluntary contributions made by many
* individuals on behalf of the Apache Software Foundation. For more
* information on the Apache Software Foundation, please see
* <http://www.apache.org/>.
*
*/
package org.apache.http.auth;
import java.util.Queue;
import org.apache.http.annotation.NotThreadSafe;
import org.apache.http.util.Args;
/**
* This class provides detailed information about the state of the authentication process.
*
* @since 4.0
*/
@NotThreadSafe
public class AuthStateHC4 {
/** Actual state of authentication protocol */
private AuthProtocolState state;
/** Actual authentication scheme */
private AuthScheme authScheme;
/** Actual authentication scope */
private AuthScope authScope;
/** Credentials selected for authentication */
private Credentials credentials;
/** Available auth options */
private Queue<AuthOption> authOptions;
public AuthStateHC4() {
super();
this.state = AuthProtocolState.UNCHALLENGED;
}
/**
* Resets the auth state.
*
* @since 4.2
*/
public void reset() {
this.state = AuthProtocolState.UNCHALLENGED;
this.authOptions = null;
this.authScheme = null;
this.authScope = null;
this.credentials = null;
}
/**
* @since 4.2
*/
public AuthProtocolState getState() {
return this.state;
}
/**
* @since 4.2
*/
public void setState(final AuthProtocolState state) {
this.state = state != null ? state : AuthProtocolState.UNCHALLENGED;
}
/**
* Returns actual {@link AuthScheme}. May be null.
*/
public AuthScheme getAuthScheme() {
return this.authScheme;
}
/**
* Returns actual {@link Credentials}. May be null.
*/
public Credentials getCredentials() {
return this.credentials;
}
/**
* Updates the auth state with {@link AuthScheme} and {@link Credentials}.
*
* @param authScheme auth scheme. May not be null.
* @param credentials user crednetials. May not be null.
*
* @since 4.2
*/
public void update(final AuthScheme authScheme, final Credentials credentials) {
Args.notNull(authScheme, "Auth scheme");
Args.notNull(credentials, "Credentials");
this.authScheme = authScheme;
this.credentials = credentials;
this.authOptions = null;
}
/**
* Returns available {@link AuthOption}s. May be null.
*
* @since 4.2
*/
public Queue<AuthOption> getAuthOptions() {
return this.authOptions;
}
/**
* Returns <code>true</code> if {@link AuthOption}s are available, <code>false</code>
* otherwise.
*
* @since 4.2
*/
public boolean hasAuthOptions() {
return this.authOptions != null && !this.authOptions.isEmpty();
}
/**
* Updates the auth state with a queue of {@link AuthOption}s.
*
* @param authOptions a queue of auth options. May not be null or empty.
*
* @since 4.2
*/
public void update(final Queue<AuthOption> authOptions) {
Args.notEmpty(authOptions, "Queue of auth options");
this.authOptions = authOptions;
this.authScheme = null;
this.credentials = null;
}
/**
* Invalidates the authentication state by resetting its parameters.
*
* @deprecated (4.2) use {@link #reset()}
*/
@Deprecated
public void invalidate() {
reset();
}
/**
* @deprecated (4.2) do not use
*/
@Deprecated
public boolean isValid() {
return this.authScheme != null;
}
/**
* Assigns the given {@link AuthScheme authentication scheme}.
*
* @param authScheme the {@link AuthScheme authentication scheme}
*
* @deprecated (4.2) use {@link #update(AuthScheme, Credentials)}
*/
@Deprecated
public void setAuthScheme(final AuthScheme authScheme) {
if (authScheme == null) {
reset();
return;
}
this.authScheme = authScheme;
}
/**
* Sets user {@link Credentials} to be used for authentication
*
* @param credentials User credentials
*
* @deprecated (4.2) use {@link #update(AuthScheme, Credentials)}
*/
@Deprecated
public void setCredentials(final Credentials credentials) {
this.credentials = credentials;
}
/**
* Returns actual {@link AuthScope} if available
*
* @return actual authentication scope if available, <code>null</code otherwise
*
* @deprecated (4.2) do not use.
*/
@Deprecated
public AuthScope getAuthScope() {
return this.authScope;
}
/**
* Sets actual {@link AuthScope}.
*
* @param authScope Authentication scope
*
* @deprecated (4.2) do not use.
*/
@Deprecated
public void setAuthScope(final AuthScope authScope) {
this.authScope = authScope;
}
@Override
public String toString() {
final StringBuilder buffer = new StringBuilder();
buffer.append("state:").append(this.state).append(";");
if (this.authScheme != null) {
buffer.append("auth scheme:").append(this.authScheme.getSchemeName()).append(";");
}
if (this.credentials != null) {
buffer.append("credentials present");
}
return buffer.toString();
}
}

View File

@ -1,38 +0,0 @@
/*
* ====================================================================
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you under the Apache License, Version 2.0 (the
* "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
* KIND, either express or implied. See the License for the
* specific language governing permissions and limitations
* under the License.
* ====================================================================
*
* This software consists of voluntary contributions made by many
* individuals on behalf of the Apache Software Foundation. For more
* information on the Apache Software Foundation, please see
* <http://www.apache.org/>.
*
*/
package org.apache.http.auth;
/**
* Challenge mode (TARGET or PROXY)
*
* @since 4.2
*/
public enum ChallengeState {
TARGET, PROXY
}

View File

@ -1,62 +0,0 @@
/*
* ====================================================================
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you under the Apache License, Version 2.0 (the
* "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
* KIND, either express or implied. See the License for the
* specific language governing permissions and limitations
* under the License.
* ====================================================================
*
* This software consists of voluntary contributions made by many
* individuals on behalf of the Apache Software Foundation. For more
* information on the Apache Software Foundation, please see
* <http://www.apache.org/>.
*
*/
package org.apache.http.auth;
import org.apache.http.Header;
import org.apache.http.HttpRequest;
import org.apache.http.protocol.HttpContext;
/**
* This interface represents an extended authentication scheme
* that requires access to {@link HttpContext} in order to
* generate an authorization string.
*
* TODO: Fix AuthScheme interface in the next major version
*
* @since 4.1
*/
public interface ContextAwareAuthScheme extends AuthScheme {
/**
* Produces an authorization string for the given set of
* {@link Credentials}.
*
* @param credentials The set of credentials to be used for athentication
* @param request The request being authenticated
* @param context HTTP context
* @throws AuthenticationException if authorization string cannot
* be generated due to an authentication failure
*
* @return the authorization string
*/
Header authenticate(
Credentials credentials,
HttpRequest request,
HttpContext context) throws AuthenticationException;
}

View File

@ -1,31 +0,0 @@
/*
* ====================================================================
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you under the Apache License, Version 2.0 (the
* "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
* KIND, either express or implied. See the License for the
* specific language governing permissions and limitations
* under the License.
* ====================================================================
*
* This software consists of voluntary contributions made by many
* individuals on behalf of the Apache Software Foundation. For more
* information on the Apache Software Foundation, please see
* <http://www.apache.org/>.
*
*/
/**
* Client HTTP authentication APIs.
*/
package org.apache.http.auth;

View File

@ -1,32 +0,0 @@
/*
* ====================================================================
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you under the Apache License, Version 2.0 (the
* "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
* KIND, either express or implied. See the License for the
* specific language governing permissions and limitations
* under the License.
* ====================================================================
*
* This software consists of voluntary contributions made by many
* individuals on behalf of the Apache Software Foundation. For more
* information on the Apache Software Foundation, please see
* <http://www.apache.org/>.
*
*/
/**
* Deprecated.
* @deprecated (4.3).
*/
package org.apache.http.auth.params;

View File

@ -1,49 +0,0 @@
/*
* ====================================================================
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you under the Apache License, Version 2.0 (the
* "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
* KIND, either express or implied. See the License for the
* specific language governing permissions and limitations
* under the License.
* ====================================================================
*
* This software consists of voluntary contributions made by many
* individuals on behalf of the Apache Software Foundation. For more
* information on the Apache Software Foundation, please see
* <http://www.apache.org/>.
*
*/
package org.apache.http.client;
import org.apache.http.HttpHost;
import org.apache.http.auth.AuthScheme;
/**
* Abstract {@link AuthScheme} cache. Initialized {@link AuthScheme} objects
* from this cache can be used to preemptively authenticate against known
* hosts.
*
* @since 4.1
*/
public interface AuthCache {
void put(HttpHost host, AuthScheme authScheme);
AuthScheme get(HttpHost host);
void remove(HttpHost host);
void clear();
}

View File

@ -1,130 +0,0 @@
/*
* ====================================================================
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you under the Apache License, Version 2.0 (the
* "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
* KIND, either express or implied. See the License for the
* specific language governing permissions and limitations
* under the License.
* ====================================================================
*
* This software consists of voluntary contributions made by many
* individuals on behalf of the Apache Software Foundation. For more
* information on the Apache Software Foundation, please see
* <http://www.apache.org/>.
*
*/
package org.apache.http.client;
import java.util.Map;
import java.util.Queue;
import org.apache.http.Header;
import org.apache.http.HttpHost;
import org.apache.http.HttpResponse;
import org.apache.http.auth.AuthOption;
import org.apache.http.auth.AuthScheme;
import org.apache.http.auth.MalformedChallengeException;
import org.apache.http.protocol.HttpContext;
/**
/**
* A handler for determining if an HTTP response represents an authentication challenge that was
* sent back to the client as a result of authentication failure.
* <p>
* Implementations of this interface must be thread-safe. Access to shared data must be
* synchronized as methods of this interface may be executed from multiple threads.
*
* @since 4.2
*/
public interface AuthenticationStrategy {
/**
* Determines if the given HTTP response response represents
* an authentication challenge that was sent back as a result
* of authentication failure.
*
* @param authhost authentication host.
* @param response HTTP response.
* @param context HTTP context.
* @return <code>true</code> if user authentication is required,
* <code>false</code> otherwise.
*/
boolean isAuthenticationRequested(
HttpHost authhost,
HttpResponse response,
HttpContext context);
/**
* Extracts from the given HTTP response a collection of authentication
* challenges, each of which represents an authentication scheme supported
* by the authentication host.
*
* @param authhost authentication host.
* @param response HTTP response.
* @param context HTTP context.
* @return a collection of challenges keyed by names of corresponding
* authentication schemes.
* @throws MalformedChallengeException if one of the authentication
* challenges is not valid or malformed.
*/
Map<String, Header> getChallenges(
HttpHost authhost,
HttpResponse response,
HttpContext context) throws MalformedChallengeException;
/**
* Selects one authentication challenge out of all available and
* creates and generates {@link AuthOption} instance capable of
* processing that challenge.
*
* @param challenges collection of challenges.
* @param authhost authentication host.
* @param response HTTP response.
* @param context HTTP context.
* @return authentication auth schemes that can be used for authentication. Can be empty.
* @throws MalformedChallengeException if one of the authentication
* challenges is not valid or malformed.
*/
Queue<AuthOption> select(
Map<String, Header> challenges,
HttpHost authhost,
HttpResponse response,
HttpContext context) throws MalformedChallengeException;
/**
* Callback invoked in case of successful authentication.
*
* @param authhost authentication host.
* @param authScheme authentication scheme used.
* @param context HTTP context.
*/
void authSucceeded(
HttpHost authhost,
AuthScheme authScheme,
HttpContext context);
/**
* Callback invoked in case of unsuccessful authentication.
*
* @param authhost authentication host.
* @param authScheme authentication scheme used.
* @param context HTTP context.
*/
void authFailed(
HttpHost authhost,
AuthScheme authScheme,
HttpContext context);
}

View File

@ -1,54 +0,0 @@
/*
* ====================================================================
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you under the Apache License, Version 2.0 (the
* "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
* KIND, either express or implied. See the License for the
* specific language governing permissions and limitations
* under the License.
* ====================================================================
*
* This software consists of voluntary contributions made by many
* individuals on behalf of the Apache Software Foundation. For more
* information on the Apache Software Foundation, please see
* <http://www.apache.org/>.
*
*/
package org.apache.http.client;
import org.apache.http.conn.routing.HttpRoute;
/**
* Represents a controller that dynamically adjusts the size
* of an available connection pool based on feedback from
* using the connections.
*
* @since 4.2
*
*/
public interface BackoffManager {
/**
* Called when we have decided that the result of
* using a connection should be interpreted as a
* backoff signal.
*/
public void backOff(HttpRoute route);
/**
* Called when we have determined that the result of
* using a connection has succeeded and that we may
* probe for more connections.
*/
public void probe(HttpRoute route);
}

View File

@ -1,64 +0,0 @@
/*
* ====================================================================
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you under the Apache License, Version 2.0 (the
* "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
* KIND, either express or implied. See the License for the
* specific language governing permissions and limitations
* under the License.
* ====================================================================
*
* This software consists of voluntary contributions made by many
* individuals on behalf of the Apache Software Foundation. For more
* information on the Apache Software Foundation, please see
* <http://www.apache.org/>.
*
*/
package org.apache.http.client;
import org.apache.http.HttpResponse;
/**
* When managing a dynamic number of connections for a given route, this
* strategy assesses whether a given request execution outcome should
* result in a backoff signal or not, based on either examining the
* <code>Throwable</code> that resulted or by examining the resulting
* response (e.g. for its status code).
*
* @since 4.2
*
*/
public interface ConnectionBackoffStrategy {
/**
* Determines whether seeing the given <code>Throwable</code> as
* a result of request execution should result in a backoff
* signal.
* @param t the <code>Throwable</code> that happened
* @return <code>true</code> if a backoff signal should be
* given
*/
boolean shouldBackoff(Throwable t);
/**
* Determines whether receiving the given {@link HttpResponse} as
* a result of request execution should result in a backoff
* signal. Implementations MUST restrict themselves to examining
* the response header and MUST NOT consume any of the response
* body, if any.
* @param resp the <code>HttpResponse</code> that was received
* @return <code>true</code> if a backoff signal should be
* given
*/
boolean shouldBackoff(HttpResponse resp);
}

View File

@ -1,81 +0,0 @@
/*
* ====================================================================
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you under the Apache License, Version 2.0 (the
* "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
* KIND, either express or implied. See the License for the
* specific language governing permissions and limitations
* under the License.
* ====================================================================
*
* This software consists of voluntary contributions made by many
* individuals on behalf of the Apache Software Foundation. For more
* information on the Apache Software Foundation, please see
* <http://www.apache.org/>.
*
*/
package org.apache.http.client;
import org.apache.http.HttpRequest;
import org.apache.http.HttpResponse;
import org.apache.http.ProtocolException;
import org.apache.http.client.methods.HttpUriRequest;
import org.apache.http.protocol.HttpContext;
/**
* A strategy for determining if an HTTP request should be redirected to
* a new location in response to an HTTP response received from the target
* server.
* <p>
* Implementations of this interface must be thread-safe. Access to shared
* data must be synchronized as methods of this interface may be executed
* from multiple threads.
*
* @since 4.1
*/
public interface RedirectStrategy {
/**
* Determines if a request should be redirected to a new location
* given the response from the target server.
*
* @param request the executed request
* @param response the response received from the target server
* @param context the context for the request execution
*
* @return <code>true</code> if the request should be redirected, <code>false</code>
* otherwise
*/
boolean isRedirected(
HttpRequest request,
HttpResponse response,
HttpContext context) throws ProtocolException;
/**
* Determines the redirect location given the response from the target
* server and the current request execution context and generates a new
* request to be sent to the location.
*
* @param request the executed request
* @param response the response received from the target server
* @param context the context for the request execution
*
* @return redirected request
*/
HttpUriRequest getRedirect(
HttpRequest request,
HttpResponse response,
HttpContext context) throws ProtocolException;
}

View File

@ -1,60 +0,0 @@
/*
* ====================================================================
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you under the Apache License, Version 2.0 (the
* "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
* KIND, either express or implied. See the License for the
* specific language governing permissions and limitations
* under the License.
* ====================================================================
*
* This software consists of voluntary contributions made by many
* individuals on behalf of the Apache Software Foundation. For more
* information on the Apache Software Foundation, please see
* <http://www.apache.org/>.
*
*/
package org.apache.http.client;
import org.apache.http.HttpResponse;
import org.apache.http.protocol.HttpContext;
/**
* Strategy interface that allows API users to plug in their own logic to
* control whether or not a retry should automatically be done, how many times
* it should be retried and so on.
*
* @since 4.2
*/
public interface ServiceUnavailableRetryStrategy {
/**
* Determines if a method should be retried given the response from the target server.
*
* @param response the response from the target server
* @param executionCount the number of times this method has been
* unsuccessfully executed
* @param context the context for the request execution
* @return <code>true</code> if the method should be retried, <code>false</code>
* otherwise
*/
boolean retryRequest(HttpResponse response, int executionCount, HttpContext context);
/**
* @return The interval between the subsequent auto-retries.
*/
long getRetryInterval();
}

View File

@ -1,71 +0,0 @@
/*
* ====================================================================
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you under the Apache License, Version 2.0 (the
* "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
* KIND, either express or implied. See the License for the
* specific language governing permissions and limitations
* under the License.
* ====================================================================
*
* This software consists of voluntary contributions made by many
* individuals on behalf of the Apache Software Foundation. For more
* information on the Apache Software Foundation, please see
* <http://www.apache.org/>.
*
*/
package org.apache.http.client.config;
import org.apache.http.annotation.Immutable;
/**
* Standard authentication schemes supported by HttpClient.
*
* @since 4.3
*/
@Immutable
public final class AuthSchemes {
/**
* Basic authentication scheme as defined in RFC2617 (considered inherently
* insecure, but most widely supported)
*/
public static final String BASIC = "Basic";
/**
* Digest authentication scheme as defined in RFC2617.
*/
public static final String DIGEST = "Digest";
/**
* The NTLM scheme is a proprietary Microsoft Windows Authentication
* protocol (considered to be the most secure among currently supported
* authentication schemes).
*/
public static final String NTLM = "NTLM";
/**
* SPNEGO Authentication scheme.
*/
public static final String SPNEGO = "negotiate";
/**
* Kerberos Authentication scheme.
*/
public static final String KERBEROS = "Kerberos";
private AuthSchemes() {
}
}

View File

@ -1,69 +0,0 @@
/*
* ====================================================================
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you under the Apache License, Version 2.0 (the
* "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
* KIND, either express or implied. See the License for the
* specific language governing permissions and limitations
* under the License.
* ====================================================================
*
* This software consists of voluntary contributions made by many
* individuals on behalf of the Apache Software Foundation. For more
* information on the Apache Software Foundation, please see
* <http://www.apache.org/>.
*
*/
package org.apache.http.client.config;
import org.apache.http.annotation.Immutable;
/**
* Standard cookie specifications supported by HttpClient.
*
* @since 4.3
*/
@Immutable
public final class CookieSpecs {
/**
* The policy that provides high degree of compatibility
* with common cookie management of popular HTTP agents.
*/
public static final String BROWSER_COMPATIBILITY = "compatibility";
/**
* The Netscape cookie draft compliant policy.
*/
public static final String NETSCAPE = "netscape";
/**
* The RFC 2965 compliant policy (standard).
*/
public static final String STANDARD = "standard";
/**
* The default 'best match' policy.
*/
public static final String BEST_MATCH = "best-match";
/**
* The policy that ignores cookies.
*/
public static final String IGNORE_COOKIES = "ignoreCookies";
private CookieSpecs() {
}
}

View File

@ -1,442 +0,0 @@
/*
* ====================================================================
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you under the Apache License, Version 2.0 (the
* "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
* KIND, either express or implied. See the License for the
* specific language governing permissions and limitations
* under the License.
* ====================================================================
*
* This software consists of voluntary contributions made by many
* individuals on behalf of the Apache Software Foundation. For more
* information on the Apache Software Foundation, please see
* <http://www.apache.org/>.
*
*/
package org.apache.http.client.config;
import java.net.InetAddress;
import java.util.Collection;
import org.apache.http.HttpHost;
public class RequestConfig implements Cloneable {
public static final RequestConfig DEFAULT = new Builder().build();
private final boolean expectContinueEnabled;
private final HttpHost proxy;
private final InetAddress localAddress;
private final boolean staleConnectionCheckEnabled;
private final String cookieSpec;
private final boolean redirectsEnabled;
private final boolean relativeRedirectsAllowed;
private final boolean circularRedirectsAllowed;
private final int maxRedirects;
private final boolean authenticationEnabled;
private final Collection<String> targetPreferredAuthSchemes;
private final Collection<String> proxyPreferredAuthSchemes;
private final int connectionRequestTimeout;
private final int connectTimeout;
private final int socketTimeout;
RequestConfig(
final boolean expectContinueEnabled,
final HttpHost proxy,
final InetAddress localAddress,
final boolean staleConnectionCheckEnabled,
final String cookieSpec,
final boolean redirectsEnabled,
final boolean relativeRedirectsAllowed,
final boolean circularRedirectsAllowed,
final int maxRedirects,
final boolean authenticationEnabled,
final Collection<String> targetPreferredAuthSchemes,
final Collection<String> proxyPreferredAuthSchemes,
final int connectionRequestTimeout,
final int connectTimeout,
final int socketTimeout) {
super();
this.expectContinueEnabled = expectContinueEnabled;
this.proxy = proxy;
this.localAddress = localAddress;
this.staleConnectionCheckEnabled = staleConnectionCheckEnabled;
this.cookieSpec = cookieSpec;
this.redirectsEnabled = redirectsEnabled;
this.relativeRedirectsAllowed = relativeRedirectsAllowed;
this.circularRedirectsAllowed = circularRedirectsAllowed;
this.maxRedirects = maxRedirects;
this.authenticationEnabled = authenticationEnabled;
this.targetPreferredAuthSchemes = targetPreferredAuthSchemes;
this.proxyPreferredAuthSchemes = proxyPreferredAuthSchemes;
this.connectionRequestTimeout = connectionRequestTimeout;
this.connectTimeout = connectTimeout;
this.socketTimeout = socketTimeout;
}
/**
* Determines whether the 'Expect: 100-Continue' handshake is enabled
* for entity enclosing methods. The purpose of the 'Expect: 100-Continue'
* handshake is to allow a client that is sending a request message with
* a request body to determine if the origin server is willing to
* accept the request (based on the request headers) before the client
* sends the request body.
* <p/>
* The use of the 'Expect: 100-continue' handshake can result in
* a noticeable performance improvement for entity enclosing requests
* (such as POST and PUT) that require the target server's
* authentication.
* <p/>
* 'Expect: 100-continue' handshake should be used with caution, as it
* may cause problems with HTTP servers and proxies that do not support
* HTTP/1.1 protocol.
* <p/>
* Default: <code>false</code>
*/
public boolean isExpectContinueEnabled() {
return expectContinueEnabled;
}
/**
* Returns HTTP proxy to be used for request execution.
* <p/>
* Default: <code>null</code>
*/
public HttpHost getProxy() {
return proxy;
}
/**
* Returns local address to be used for request execution.
* <p/>
* On machines with multiple network interfaces, this parameter
* can be used to select the network interface from which the
* connection originates.
* <p/>
* Default: <code>null</code>
*/
public InetAddress getLocalAddress() {
return localAddress;
}
/**
* Determines whether stale connection check is to be used. The stale
* connection check can cause up to 30 millisecond overhead per request and
* should be used only when appropriate. For performance critical
* operations this check should be disabled.
* <p/>
* Default: <code>true</code>
*/
public boolean isStaleConnectionCheckEnabled() {
return staleConnectionCheckEnabled;
}
/**
* Determines the name of the cookie specification to be used for HTTP state
* management.
* <p/>
* Default: <code>null</code>
*/
public String getCookieSpec() {
return cookieSpec;
}
/**
* Determines whether redirects should be handled automatically.
* <p/>
* Default: <code>true</code>
*/
public boolean isRedirectsEnabled() {
return redirectsEnabled;
}
/**
* Determines whether relative redirects should be rejected. HTTP specification
* requires the location value be an absolute URI.
* <p/>
* Default: <code>true</code>
*/
public boolean isRelativeRedirectsAllowed() {
return relativeRedirectsAllowed;
}
/**
* Determines whether circular redirects (redirects to the same location) should
* be allowed. The HTTP spec is not sufficiently clear whether circular redirects
* are permitted, therefore optionally they can be enabled
* <p/>
* Default: <code>false</code>
*/
public boolean isCircularRedirectsAllowed() {
return circularRedirectsAllowed;
}
/**
* Returns the maximum number of redirects to be followed. The limit on number
* of redirects is intended to prevent infinite loops.
* <p/>
* Default: <code>50</code>
*/
public int getMaxRedirects() {
return maxRedirects;
}
/**
* Determines whether authentication should be handled automatically.
* <p/>
* Default: <code>true</code>
*/
public boolean isAuthenticationEnabled() {
return authenticationEnabled;
}
/**
* Determines the order of preference for supported authentication schemes
* when authenticating with the target host.
* <p/>
* Default: <code>null</code>
*/
public Collection<String> getTargetPreferredAuthSchemes() {
return targetPreferredAuthSchemes;
}
/**
* Determines the order of preference for supported authentication schemes
* when authenticating with the proxy host.
* <p/>
* Default: <code>null</code>
*/
public Collection<String> getProxyPreferredAuthSchemes() {
return proxyPreferredAuthSchemes;
}
/**
* Returns the timeout in milliseconds used when requesting a connection
* from the connection manager. A timeout value of zero is interpreted
* as an infinite timeout.
* <p/>
* A timeout value of zero is interpreted as an infinite timeout.
* A negative value is interpreted as undefined (system default).
* <p/>
* Default: <code>-1</code>
*/
public int getConnectionRequestTimeout() {
return connectionRequestTimeout;
}
/**
* Determines the timeout in milliseconds until a connection is established.
* A timeout value of zero is interpreted as an infinite timeout.
* <p/>
* A timeout value of zero is interpreted as an infinite timeout.
* A negative value is interpreted as undefined (system default).
* <p/>
* Default: <code>-1</code>
*/
public int getConnectTimeout() {
return connectTimeout;
}
/**
* Defines the socket timeout (<code>SO_TIMEOUT</code>) in milliseconds,
* which is the timeout for waiting for data or, put differently,
* a maximum period inactivity between two consecutive data packets).
* <p/>
* A timeout value of zero is interpreted as an infinite timeout.
* A negative value is interpreted as undefined (system default).
* <p/>
* Default: <code>-1</code>
*/
public int getSocketTimeout() {
return socketTimeout;
}
@Override
protected RequestConfig clone() throws CloneNotSupportedException {
return (RequestConfig) super.clone();
}
@Override
public String toString() {
final StringBuilder builder = new StringBuilder();
builder.append(", expectContinueEnabled=").append(expectContinueEnabled);
builder.append(", proxy=").append(proxy);
builder.append(", localAddress=").append(localAddress);
builder.append(", staleConnectionCheckEnabled=").append(staleConnectionCheckEnabled);
builder.append(", cookieSpec=").append(cookieSpec);
builder.append(", redirectsEnabled=").append(redirectsEnabled);
builder.append(", relativeRedirectsAllowed=").append(relativeRedirectsAllowed);
builder.append(", maxRedirects=").append(maxRedirects);
builder.append(", circularRedirectsAllowed=").append(circularRedirectsAllowed);
builder.append(", authenticationEnabled=").append(authenticationEnabled);
builder.append(", targetPreferredAuthSchemes=").append(targetPreferredAuthSchemes);
builder.append(", proxyPreferredAuthSchemes=").append(proxyPreferredAuthSchemes);
builder.append(", connectionRequestTimeout=").append(connectionRequestTimeout);
builder.append(", connectTimeout=").append(connectTimeout);
builder.append(", socketTimeout=").append(socketTimeout);
builder.append("]");
return builder.toString();
}
public static RequestConfig.Builder custom() {
return new Builder();
}
public static RequestConfig.Builder copy(final RequestConfig config) {
return new Builder()
.setExpectContinueEnabled(config.isExpectContinueEnabled())
.setProxy(config.getProxy())
.setLocalAddress(config.getLocalAddress())
.setStaleConnectionCheckEnabled(config.isStaleConnectionCheckEnabled())
.setCookieSpec(config.getCookieSpec())
.setRedirectsEnabled(config.isRedirectsEnabled())
.setRelativeRedirectsAllowed(config.isRelativeRedirectsAllowed())
.setCircularRedirectsAllowed(config.isCircularRedirectsAllowed())
.setMaxRedirects(config.getMaxRedirects())
.setAuthenticationEnabled(config.isAuthenticationEnabled())
.setTargetPreferredAuthSchemes(config.getTargetPreferredAuthSchemes())
.setProxyPreferredAuthSchemes(config.getProxyPreferredAuthSchemes())
.setConnectionRequestTimeout(config.getConnectionRequestTimeout())
.setConnectTimeout(config.getConnectTimeout())
.setSocketTimeout(config.getSocketTimeout());
}
public static class Builder {
private boolean expectContinueEnabled;
private HttpHost proxy;
private InetAddress localAddress;
private boolean staleConnectionCheckEnabled;
private String cookieSpec;
private boolean redirectsEnabled;
private boolean relativeRedirectsAllowed;
private boolean circularRedirectsAllowed;
private int maxRedirects;
private boolean authenticationEnabled;
private Collection<String> targetPreferredAuthSchemes;
private Collection<String> proxyPreferredAuthSchemes;
private int connectionRequestTimeout;
private int connectTimeout;
private int socketTimeout;
Builder() {
super();
this.staleConnectionCheckEnabled = true;
this.redirectsEnabled = true;
this.maxRedirects = 50;
this.relativeRedirectsAllowed = true;
this.authenticationEnabled = true;
this.connectionRequestTimeout = -1;
this.connectTimeout = -1;
this.socketTimeout = -1;
}
public Builder setExpectContinueEnabled(final boolean expectContinueEnabled) {
this.expectContinueEnabled = expectContinueEnabled;
return this;
}
public Builder setProxy(final HttpHost proxy) {
this.proxy = proxy;
return this;
}
public Builder setLocalAddress(final InetAddress localAddress) {
this.localAddress = localAddress;
return this;
}
public Builder setStaleConnectionCheckEnabled(final boolean staleConnectionCheckEnabled) {
this.staleConnectionCheckEnabled = staleConnectionCheckEnabled;
return this;
}
public Builder setCookieSpec(final String cookieSpec) {
this.cookieSpec = cookieSpec;
return this;
}
public Builder setRedirectsEnabled(final boolean redirectsEnabled) {
this.redirectsEnabled = redirectsEnabled;
return this;
}
public Builder setRelativeRedirectsAllowed(final boolean relativeRedirectsAllowed) {
this.relativeRedirectsAllowed = relativeRedirectsAllowed;
return this;
}
public Builder setCircularRedirectsAllowed(final boolean circularRedirectsAllowed) {
this.circularRedirectsAllowed = circularRedirectsAllowed;
return this;
}
public Builder setMaxRedirects(final int maxRedirects) {
this.maxRedirects = maxRedirects;
return this;
}
public Builder setAuthenticationEnabled(final boolean authenticationEnabled) {
this.authenticationEnabled = authenticationEnabled;
return this;
}
public Builder setTargetPreferredAuthSchemes(final Collection<String> targetPreferredAuthSchemes) {
this.targetPreferredAuthSchemes = targetPreferredAuthSchemes;
return this;
}
public Builder setProxyPreferredAuthSchemes(final Collection<String> proxyPreferredAuthSchemes) {
this.proxyPreferredAuthSchemes = proxyPreferredAuthSchemes;
return this;
}
public Builder setConnectionRequestTimeout(final int connectionRequestTimeout) {
this.connectionRequestTimeout = connectionRequestTimeout;
return this;
}
public Builder setConnectTimeout(final int connectTimeout) {
this.connectTimeout = connectTimeout;
return this;
}
public Builder setSocketTimeout(final int socketTimeout) {
this.socketTimeout = socketTimeout;
return this;
}
public RequestConfig build() {
return new RequestConfig(
expectContinueEnabled,
proxy,
localAddress,
staleConnectionCheckEnabled,
cookieSpec,
redirectsEnabled,
relativeRedirectsAllowed,
circularRedirectsAllowed,
maxRedirects,
authenticationEnabled,
targetPreferredAuthSchemes,
proxyPreferredAuthSchemes,
connectionRequestTimeout,
connectTimeout,
socketTimeout);
}
}
}

View File

@ -1,31 +0,0 @@
/*
* ====================================================================
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you under the Apache License, Version 2.0 (the
* "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
* KIND, either express or implied. See the License for the
* specific language governing permissions and limitations
* under the License.
* ====================================================================
*
* This software consists of voluntary contributions made by many
* individuals on behalf of the Apache Software Foundation. For more
* information on the Apache Software Foundation, please see
* <http://www.apache.org/>.
*
*/
/**
* Client configuration APIs.
*/
package org.apache.http.client.config;

View File

@ -1,105 +0,0 @@
/*
* ====================================================================
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you under the Apache License, Version 2.0 (the
* "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
* KIND, either express or implied. See the License for the
* specific language governing permissions and limitations
* under the License.
* ====================================================================
*
* This software consists of voluntary contributions made by many
* individuals on behalf of the Apache Software Foundation. For more
* information on the Apache Software Foundation, please see
* <http://www.apache.org/>.
*
*/
package org.apache.http.client.entity;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import org.apache.http.HttpEntity;
import org.apache.http.entity.HttpEntityWrapperHC4;
import org.apache.http.util.Args;
/**
* Common base class for decompressing {@link HttpEntity} implementations.
*
* @since 4.1
*/
abstract class DecompressingEntity extends HttpEntityWrapperHC4 {
/**
* Default buffer size.
*/
private static final int BUFFER_SIZE = 1024 * 2;
/**
* {@link #getContent()} method must return the same {@link InputStream}
* instance when DecompressingEntity is wrapping a streaming entity.
*/
private InputStream content;
/**
* Creates a new {@link DecompressingEntity}.
*
* @param wrapped
* the non-null {@link HttpEntity} to be wrapped
*/
public DecompressingEntity(final HttpEntity wrapped) {
super(wrapped);
}
abstract InputStream decorate(final InputStream wrapped) throws IOException;
private InputStream getDecompressingStream() throws IOException {
final InputStream in = wrappedEntity.getContent();
return new LazyDecompressingInputStream(in, this);
}
/**
* {@inheritDoc}
*/
@Override
public InputStream getContent() throws IOException {
if (wrappedEntity.isStreaming()) {
if (content == null) {
content = getDecompressingStream();
}
return content;
} else {
return getDecompressingStream();
}
}
/**
* {@inheritDoc}
*/
@Override
public void writeTo(final OutputStream outstream) throws IOException {
Args.notNull(outstream, "Output stream");
final InputStream instream = getContent();
try {
final byte[] buffer = new byte[BUFFER_SIZE];
int l;
while ((l = instream.read(buffer)) != -1) {
outstream.write(buffer, 0, l);
}
} finally {
instream.close();
}
}
}

View File

@ -1,96 +0,0 @@
/*
* ====================================================================
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you under the Apache License, Version 2.0 (the
* "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
* KIND, either express or implied. See the License for the
* specific language governing permissions and limitations
* under the License.
* ====================================================================
*
* This software consists of voluntary contributions made by many
* individuals on behalf of the Apache Software Foundation. For more
* information on the Apache Software Foundation, please see
* <http://www.apache.org/>.
*
*/
package org.apache.http.client.entity;
import java.io.IOException;
import java.io.InputStream;
import org.apache.http.Header;
import org.apache.http.HttpEntity;
/**
* {@link org.apache.http.entity.HttpEntityWrapper} responsible for handling
* deflate Content Coded responses. In RFC2616 terms, <code>deflate</code>
* means a <code>zlib</code> stream as defined in RFC1950. Some server
* implementations have misinterpreted RFC2616 to mean that a
* <code>deflate</code> stream as defined in RFC1951 should be used
* (or maybe they did that since that's how IE behaves?). It's confusing
* that <code>deflate</code> in HTTP 1.1 means <code>zlib</code> streams
* rather than <code>deflate</code> streams. We handle both types in here,
* since that's what is seen on the internet. Moral - prefer
* <code>gzip</code>!
*
* @see GzipDecompressingEntity
*
* @since 4.1
*/
public class DeflateDecompressingEntity extends DecompressingEntity {
/**
* Creates a new {@link DeflateDecompressingEntity} which will wrap the specified
* {@link HttpEntity}.
*
* @param entity
* a non-null {@link HttpEntity} to be wrapped
*/
public DeflateDecompressingEntity(final HttpEntity entity) {
super(entity);
}
/**
* Returns the non-null InputStream that should be returned to by all requests to
* {@link #getContent()}.
*
* @return a non-null InputStream
* @throws IOException if there was a problem
*/
@Override
InputStream decorate(final InputStream wrapped) throws IOException {
return new DeflateInputStream(wrapped);
}
/**
* {@inheritDoc}
*/
@Override
public Header getContentEncoding() {
/* This HttpEntityWrapperHC4 has dealt with the Content-Encoding. */
return null;
}
/**
* {@inheritDoc}
*/
@Override
public long getContentLength() {
/* Length of inflated content is unknown. */
return -1;
}
}

View File

@ -1,229 +0,0 @@
/*
* ====================================================================
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you under the Apache License, Version 2.0 (the
* "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
* KIND, either express or implied. See the License for the
* specific language governing permissions and limitations
* under the License.
* ====================================================================
*
* This software consists of voluntary contributions made by many
* individuals on behalf of the Apache Software Foundation. For more
* information on the Apache Software Foundation, please see
* <http://www.apache.org/>.
*
*/
package org.apache.http.client.entity;
import java.io.IOException;
import java.io.InputStream;
import java.io.PushbackInputStream;
import java.util.zip.DataFormatException;
import java.util.zip.Inflater;
import java.util.zip.InflaterInputStream;
/** Deflate input stream. This class includes logic needed for various Rfc's in order
* to reasonably implement the "deflate" compression style.
*/
public class DeflateInputStream extends InputStream
{
private InputStream sourceStream;
public DeflateInputStream(final InputStream wrapped)
throws IOException
{
/*
* A zlib stream will have a header.
*
* CMF | FLG [| DICTID ] | ...compressed data | ADLER32 |
*
* * CMF is one byte.
*
* * FLG is one byte.
*
* * DICTID is four bytes, and only present if FLG.FDICT is set.
*
* Sniff the content. Does it look like a zlib stream, with a CMF, etc? c.f. RFC1950,
* section 2.2. http://tools.ietf.org/html/rfc1950#page-4
*
* We need to see if it looks like a proper zlib stream, or whether it is just a deflate
* stream. RFC2616 calls zlib streams deflate. Confusing, isn't it? That's why some servers
* implement deflate Content-Encoding using deflate streams, rather than zlib streams.
*
* We could start looking at the bytes, but to be honest, someone else has already read
* the RFCs and implemented that for us. So we'll just use the JDK libraries and exception
* handling to do this. If that proves slow, then we could potentially change this to check
* the first byte - does it look like a CMF? What about the second byte - does it look like
* a FLG, etc.
*/
/* We read a small buffer to sniff the content. */
final byte[] peeked = new byte[6];
final PushbackInputStream pushback = new PushbackInputStream(wrapped, peeked.length);
final int headerLength = pushback.read(peeked);
if (headerLength == -1) {
throw new IOException("Unable to read the response");
}
/* We try to read the first uncompressed byte. */
final byte[] dummy = new byte[1];
final Inflater inf = new Inflater();
try {
int n;
while ((n = inf.inflate(dummy)) == 0) {
if (inf.finished()) {
/* Not expecting this, so fail loudly. */
throw new IOException("Unable to read the response");
}
if (inf.needsDictionary()) {
/* Need dictionary - then it must be zlib stream with DICTID part? */
break;
}
if (inf.needsInput()) {
inf.setInput(peeked);
}
}
if (n == -1) {
throw new IOException("Unable to read the response");
}
/*
* We read something without a problem, so it's a valid zlib stream. Just need to reset
* and return an unused InputStream now.
*/
pushback.unread(peeked, 0, headerLength);
sourceStream = new DeflateStream(pushback, new Inflater());
} catch (final DataFormatException e) {
/* Presume that it's an RFC1951 deflate stream rather than RFC1950 zlib stream and try
* again. */
pushback.unread(peeked, 0, headerLength);
sourceStream = new DeflateStream(pushback, new Inflater(true));
} finally {
inf.end();
}
}
/** Read a byte.
*/
@Override
public int read()
throws IOException
{
return sourceStream.read();
}
/** Read lots of bytes.
*/
@Override
public int read(final byte[] b)
throws IOException
{
return sourceStream.read(b);
}
/** Read lots of specific bytes.
*/
@Override
public int read(final byte[] b, final int off, final int len)
throws IOException
{
return sourceStream.read(b,off,len);
}
/** Skip
*/
@Override
public long skip(final long n)
throws IOException
{
return sourceStream.skip(n);
}
/** Get available.
*/
@Override
public int available()
throws IOException
{
return sourceStream.available();
}
/** Mark.
*/
@Override
public void mark(final int readLimit)
{
sourceStream.mark(readLimit);
}
/** Reset.
*/
@Override
public void reset()
throws IOException
{
sourceStream.reset();
}
/** Check if mark is supported.
*/
@Override
public boolean markSupported()
{
return sourceStream.markSupported();
}
/** Close.
*/
@Override
public void close()
throws IOException
{
sourceStream.close();
}
static class DeflateStream extends InflaterInputStream {
private boolean closed = false;
public DeflateStream(final InputStream in, final Inflater inflater) {
super(in, inflater);
}
@Override
public void close() throws IOException {
if (closed) {
return;
}
closed = true;
inf.end();
super.close();
}
}
}

View File

@ -1,342 +0,0 @@
/*
* ====================================================================
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you under the Apache License, Version 2.0 (the
* "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
* KIND, either express or implied. See the License for the
* specific language governing permissions and limitations
* under the License.
* ====================================================================
*
* This software consists of voluntary contributions made by many
* individuals on behalf of the Apache Software Foundation. For more
* information on the Apache Software Foundation, please see
* <http://www.apache.org/>.
*
*/
package org.apache.http.client.entity;
import java.io.File;
import java.io.InputStream;
import java.io.Serializable;
import java.util.Arrays;
import java.util.List;
import org.apache.http.HttpEntity;
import org.apache.http.NameValuePair;
import org.apache.http.annotation.NotThreadSafe;
import org.apache.http.entity.AbstractHttpEntityHC4;
import org.apache.http.entity.BasicHttpEntityHC4;
import org.apache.http.entity.ByteArrayEntityHC4;
import org.apache.http.entity.ContentType;
import org.apache.http.entity.FileEntityHC4;
import org.apache.http.entity.InputStreamEntityHC4;
import org.apache.http.entity.SerializableEntityHC4;
import org.apache.http.entity.StringEntityHC4;
/**
* Builder for {@link HttpEntity} instances.
* <p/>
* Several setter methods of this builder are mutually exclusive. In case of multiple invocations
* of the following methods only the last one will have effect:
* <ul>
* <li>{@link #setText(String)}</li>
* <li>{@link #setBinary(byte[])}</li>
* <li>{@link #setStream(java.io.InputStream)}</li>
* <li>{@link #setSerializable(java.io.Serializable)}</li>
* <li>{@link #setParameters(java.util.List)}</li>
* <li>{@link #setParameters(org.apache.http.NameValuePair...)}</li>
* <li>{@link #setFile(java.io.File)}</li>
* </ul>
*
* @since 4.3
*/
@NotThreadSafe
public class EntityBuilder {
private String text;
private byte[] binary;
private InputStream stream;
private List<NameValuePair> parameters;
private Serializable serializable;
private File file;
private ContentType contentType;
private String contentEncoding;
private boolean chunked;
private boolean gzipCompress;
EntityBuilder() {
super();
}
public static EntityBuilder create() {
return new EntityBuilder();
}
private void clearContent() {
this.text = null;
this.binary = null;
this.stream = null;
this.parameters = null;
this.serializable = null;
this.file = null;
}
/**
* Returns entity content as a string if set using {@link #setText(String)} method.
*/
public String getText() {
return text;
}
/**
* Sets entity content as a string. This method is mutually exclusive with
* {@link #setBinary(byte[])},
* {@link #setStream(java.io.InputStream)} ,
* {@link #setSerializable(java.io.Serializable)} ,
* {@link #setParameters(java.util.List)},
* {@link #setParameters(org.apache.http.NameValuePair...)}
* {@link #setFile(java.io.File)} methods.
*/
public EntityBuilder setText(final String text) {
clearContent();
this.text = text;
return this;
}
/**
* Returns entity content as a byte array if set using
* {@link #setBinary(byte[])} method.
*/
public byte[] getBinary() {
return binary;
}
/**
* Sets entity content as a byte array. This method is mutually exclusive with
* {@link #setText(String)},
* {@link #setStream(java.io.InputStream)} ,
* {@link #setSerializable(java.io.Serializable)} ,
* {@link #setParameters(java.util.List)},
* {@link #setParameters(org.apache.http.NameValuePair...)}
* {@link #setFile(java.io.File)} methods.
*/
public EntityBuilder setBinary(final byte[] binary) {
clearContent();
this.binary = binary;
return this;
}
/**
* Returns entity content as a {@link InputStream} if set using
* {@link #setStream(java.io.InputStream)} method.
*/
public InputStream getStream() {
return stream;
}
/**
* Sets entity content as a {@link InputStream}. This method is mutually exclusive with
* {@link #setText(String)},
* {@link #setBinary(byte[])},
* {@link #setSerializable(java.io.Serializable)} ,
* {@link #setParameters(java.util.List)},
* {@link #setParameters(org.apache.http.NameValuePair...)}
* {@link #setFile(java.io.File)} methods.
*/
public EntityBuilder setStream(final InputStream stream) {
clearContent();
this.stream = stream;
return this;
}
/**
* Returns entity content as a parameter list if set using
* {@link #setParameters(java.util.List)} or
* {@link #setParameters(org.apache.http.NameValuePair...)} methods.
*/
public List<NameValuePair> getParameters() {
return parameters;
}
/**
* Sets entity content as a parameter list. This method is mutually exclusive with
* {@link #setText(String)},
* {@link #setBinary(byte[])},
* {@link #setStream(java.io.InputStream)} ,
* {@link #setSerializable(java.io.Serializable)} ,
* {@link #setFile(java.io.File)} methods.
*/
public EntityBuilder setParameters(final List<NameValuePair> parameters) {
clearContent();
this.parameters = parameters;
return this;
}
/**
* Sets entity content as a parameter list. This method is mutually exclusive with
* {@link #setText(String)},
* {@link #setBinary(byte[])},
* {@link #setStream(java.io.InputStream)} ,
* {@link #setSerializable(java.io.Serializable)} ,
* {@link #setFile(java.io.File)} methods.
*/
public EntityBuilder setParameters(final NameValuePair... parameters) {
return setParameters(Arrays.asList(parameters));
}
/**
* Returns entity content as a {@link Serializable} if set using
* {@link #setSerializable(java.io.Serializable)} method.
*/
public Serializable getSerializable() {
return serializable;
}
/**
* Sets entity content as a {@link Serializable}. This method is mutually exclusive with
* {@link #setText(String)},
* {@link #setBinary(byte[])},
* {@link #setStream(java.io.InputStream)} ,
* {@link #setParameters(java.util.List)},
* {@link #setParameters(org.apache.http.NameValuePair...)}
* {@link #setFile(java.io.File)} methods.
*/
public EntityBuilder setSerializable(final Serializable serializable) {
clearContent();
this.serializable = serializable;
return this;
}
/**
* Returns entity content as a {@link File} if set using
* {@link #setFile(java.io.File)} method.
*/
public File getFile() {
return file;
}
/**
* Sets entity content as a {@link File}. This method is mutually exclusive with
* {@link #setText(String)},
* {@link #setBinary(byte[])},
* {@link #setStream(java.io.InputStream)} ,
* {@link #setParameters(java.util.List)},
* {@link #setParameters(org.apache.http.NameValuePair...)}
* {@link #setSerializable(java.io.Serializable)} methods.
*/
public EntityBuilder setFile(final File file) {
clearContent();
this.file = file;
return this;
}
/**
* Returns {@link ContentType} of the entity, if set.
*/
public ContentType getContentType() {
return contentType;
}
/**
* Sets {@link ContentType} of the entity.
*/
public EntityBuilder setContentType(final ContentType contentType) {
this.contentType = contentType;
return this;
}
/**
* Returns content encoding of the entity, if set.
*/
public String getContentEncoding() {
return contentEncoding;
}
/**
* Sets content encoding of the entity.
*/
public EntityBuilder setContentEncoding(final String contentEncoding) {
this.contentEncoding = contentEncoding;
return this;
}
/**
* Returns <code>true</code> if entity is to be chunk coded, <code>false</code> otherwise.
*/
public boolean isChunked() {
return chunked;
}
/**
* Makes entity chunk coded.
*/
public EntityBuilder chunked() {
this.chunked = true;
return this;
}
/**
* Returns <code>true</code> if entity is to be GZIP compressed, <code>false</code> otherwise.
*/
public boolean isGzipCompress() {
return gzipCompress;
}
/**
* Makes entity GZIP compressed.
*/
public EntityBuilder gzipCompress() {
this.gzipCompress = true;
return this;
}
private ContentType getContentOrDefault(final ContentType def) {
return this.contentType != null ? this.contentType : def;
}
/**
* Creates new instance of {@link HttpEntity} based on the current state.
*/
public HttpEntity build() {
final AbstractHttpEntityHC4 e;
if (this.text != null) {
e = new StringEntityHC4(this.text, getContentOrDefault(ContentType.DEFAULT_TEXT));
} else if (this.binary != null) {
e = new ByteArrayEntityHC4(this.binary, getContentOrDefault(ContentType.DEFAULT_BINARY));
} else if (this.stream != null) {
e = new InputStreamEntityHC4(this.stream, 1, getContentOrDefault(ContentType.DEFAULT_BINARY));
} else if (this.parameters != null) {
e = new UrlEncodedFormEntityHC4(this.parameters,
this.contentType != null ? this.contentType.getCharset() : null);
} else if (this.serializable != null) {
e = new SerializableEntityHC4(this.serializable);
e.setContentType(ContentType.DEFAULT_BINARY.toString());
} else if (this.file != null) {
e = new FileEntityHC4(this.file, getContentOrDefault(ContentType.DEFAULT_BINARY));
} else {
e = new BasicHttpEntityHC4();
}
if (e.getContentType() != null && this.contentType != null) {
e.setContentType(this.contentType.toString());
}
e.setContentEncoding(this.contentEncoding);
e.setChunked(this.chunked);
if (this.gzipCompress) {
return new GzipCompressingEntity(e);
}
return e;
}
}

View File

@ -1,113 +0,0 @@
/*
* ====================================================================
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you under the Apache License, Version 2.0 (the
* "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
* KIND, either express or implied. See the License for the
* specific language governing permissions and limitations
* under the License.
* ====================================================================
*
* This software consists of voluntary contributions made by many
* individuals on behalf of the Apache Software Foundation. For more
* information on the Apache Software Foundation, please see
* <http://www.apache.org/>.
*
*/
package org.apache.http.client.entity;
/*
* ====================================================================
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you under the Apache License, Version 2.0 (the
* "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
* KIND, either express or implied. See the License for the
* specific language governing permissions and limitations
* under the License.
* ====================================================================
*
* This software consists of voluntary contributions made by many
* individuals on behalf of the Apache Software Foundation. For more
* information on the Apache Software Foundation, please see
* <http://www.apache.org/>.
*
*/
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.util.zip.GZIPOutputStream;
import org.apache.http.Header;
import org.apache.http.HttpEntity;
import org.apache.http.entity.HttpEntityWrapperHC4;
import org.apache.http.message.BasicHeader;
import org.apache.http.protocol.HTTP;
import org.apache.http.util.Args;
/**
* Wrapping entity that compresses content when {@link #writeTo writing}.
*
*
* @since 4.0
*/
public class GzipCompressingEntity extends HttpEntityWrapperHC4 {
private static final String GZIP_CODEC = "gzip";
public GzipCompressingEntity(final HttpEntity entity) {
super(entity);
}
@Override
public Header getContentEncoding() {
return new BasicHeader(HTTP.CONTENT_ENCODING, GZIP_CODEC);
}
@Override
public long getContentLength() {
return -1;
}
@Override
public boolean isChunked() {
// force content chunking
return true;
}
@Override
public InputStream getContent() throws IOException {
throw new UnsupportedOperationException();
}
@Override
public void writeTo(final OutputStream outstream) throws IOException {
Args.notNull(outstream, "Output stream");
final GZIPOutputStream gzip = new GZIPOutputStream(outstream);
wrappedEntity.writeTo(gzip);
// Only close output stream if the wrapped entity has been
// successfully written out
gzip.close();
}
}

View File

@ -1,80 +0,0 @@
/*
* ====================================================================
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you under the Apache License, Version 2.0 (the
* "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
* KIND, either express or implied. See the License for the
* specific language governing permissions and limitations
* under the License.
* ====================================================================
*
* This software consists of voluntary contributions made by many
* individuals on behalf of the Apache Software Foundation. For more
* information on the Apache Software Foundation, please see
* <http://www.apache.org/>.
*
*/
package org.apache.http.client.entity;
import java.io.IOException;
import java.io.InputStream;
import java.util.zip.GZIPInputStream;
import org.apache.http.Header;
import org.apache.http.HttpEntity;
/**
* {@link org.apache.http.entity.HttpEntityWrapper} for handling gzip
* Content Coded responses.
*
* @since 4.1
*/
public class GzipDecompressingEntity extends DecompressingEntity {
/**
* Creates a new {@link GzipDecompressingEntity} which will wrap the specified
* {@link HttpEntity}.
*
* @param entity
* the non-null {@link HttpEntity} to be wrapped
*/
public GzipDecompressingEntity(final HttpEntity entity) {
super(entity);
}
@Override
InputStream decorate(final InputStream wrapped) throws IOException {
return new GZIPInputStream(wrapped);
}
/**
* {@inheritDoc}
*/
@Override
public Header getContentEncoding() {
/* This HttpEntityWrapperHC4 has dealt with the Content-Encoding. */
return null;
}
/**
* {@inheritDoc}
*/
@Override
public long getContentLength() {
/* length of ungzipped content is not known */
return -1;
}
}

View File

@ -1,105 +0,0 @@
/*
* ====================================================================
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you under the Apache License, Version 2.0 (the
* "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
* KIND, either express or implied. See the License for the
* specific language governing permissions and limitations
* under the License.
* ====================================================================
*
* This software consists of voluntary contributions made by many
* individuals on behalf of the Apache Software Foundation. For more
* information on the Apache Software Foundation, please see
* <http://www.apache.org/>.
*
*/
package org.apache.http.client.entity;
import org.apache.http.annotation.NotThreadSafe;
import java.io.IOException;
import java.io.InputStream;
/**
* Lazy init InputStream wrapper.
*/
@NotThreadSafe
class LazyDecompressingInputStream extends InputStream {
private final InputStream wrappedStream;
private final DecompressingEntity decompressingEntity;
private InputStream wrapperStream;
public LazyDecompressingInputStream(
final InputStream wrappedStream,
final DecompressingEntity decompressingEntity) {
this.wrappedStream = wrappedStream;
this.decompressingEntity = decompressingEntity;
}
private void initWrapper() throws IOException {
if (wrapperStream == null) {
wrapperStream = decompressingEntity.decorate(wrappedStream);
}
}
@Override
public int read() throws IOException {
initWrapper();
return wrapperStream.read();
}
@Override
public int read(final byte[] b) throws IOException {
initWrapper();
return wrapperStream.read(b);
}
@Override
public int read(final byte[] b, final int off, final int len) throws IOException {
initWrapper();
return wrapperStream.read(b, off, len);
}
@Override
public long skip(final long n) throws IOException {
initWrapper();
return wrapperStream.skip(n);
}
@Override
public boolean markSupported() {
return false;
}
@Override
public int available() throws IOException {
initWrapper();
return wrapperStream.available();
}
@Override
public void close() throws IOException {
try {
if (wrapperStream != null) {
wrapperStream.close();
}
} finally {
wrappedStream.close();
}
}
}

View File

@ -1,107 +0,0 @@
/*
* ====================================================================
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you under the Apache License, Version 2.0 (the
* "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
* KIND, either express or implied. See the License for the
* specific language governing permissions and limitations
* under the License.
* ====================================================================
*
* This software consists of voluntary contributions made by many
* individuals on behalf of the Apache Software Foundation. For more
* information on the Apache Software Foundation, please see
* <http://www.apache.org/>.
*
*/
package org.apache.http.client.entity;
import java.io.UnsupportedEncodingException;
import java.nio.charset.Charset;
import java.util.List;
import org.apache.http.NameValuePair;
import org.apache.http.annotation.NotThreadSafe;
import org.apache.http.client.utils.URLEncodedUtilsHC4;
import org.apache.http.entity.ContentType;
import org.apache.http.entity.StringEntityHC4;
import org.apache.http.protocol.HTTP;
/**
* An entity composed of a list of url-encoded pairs.
* This is typically useful while sending an HTTP POST request.
*
* @since 4.0
*/
@NotThreadSafe // AbstractHttpEntityHC4 is not thread-safe
public class UrlEncodedFormEntityHC4 extends StringEntityHC4 {
/**
* Constructs a new {@link UrlEncodedFormEntity} with the list
* of parameters in the specified encoding.
*
* @param parameters list of name/value pairs
* @param charset encoding the name/value pairs be encoded with
* @throws UnsupportedEncodingException if the encoding isn't supported
*/
public UrlEncodedFormEntityHC4 (
final List <? extends NameValuePair> parameters,
final String charset) throws UnsupportedEncodingException {
super(URLEncodedUtilsHC4.format(parameters,
charset != null ? charset : Charset.forName(HTTP.DEFAULT_CONTENT_CHARSET).name()),
ContentType.create(URLEncodedUtilsHC4.CONTENT_TYPE, charset));
}
/**
* Constructs a new {@link UrlEncodedFormEntity} with the list
* of parameters in the specified encoding.
*
* @param parameters iterable collection of name/value pairs
* @param charset encoding the name/value pairs be encoded with
*
* @since 4.2
*/
public UrlEncodedFormEntityHC4 (
final Iterable <? extends NameValuePair> parameters,
final Charset charset) {
super(URLEncodedUtilsHC4.format(parameters,
charset != null ? charset : Charset.forName(HTTP.DEFAULT_CONTENT_CHARSET)),
ContentType.create(URLEncodedUtilsHC4.CONTENT_TYPE, charset));
}
/**
* Constructs a new {@link UrlEncodedFormEntity} with the list
* of parameters with the default encoding of {@link HTTP#DEFAULT_CONTENT_CHARSET}
*
* @param parameters list of name/value pairs
* @throws UnsupportedEncodingException if the default encoding isn't supported
*/
public UrlEncodedFormEntityHC4 (
final List <? extends NameValuePair> parameters) throws UnsupportedEncodingException {
this(parameters, (Charset) null);
}
/**
* Constructs a new {@link UrlEncodedFormEntity} with the list
* of parameters with the default encoding of {@link HTTP#DEFAULT_CONTENT_CHARSET}
*
* @param parameters iterable collection of name/value pairs
*
* @since 4.2
*/
public UrlEncodedFormEntityHC4 (
final Iterable <? extends NameValuePair> parameters) {
this(parameters, null);
}
}

View File

@ -1,31 +0,0 @@
/*
* ====================================================================
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you under the Apache License, Version 2.0 (the
* "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
* KIND, either express or implied. See the License for the
* specific language governing permissions and limitations
* under the License.
* ====================================================================
*
* This software consists of voluntary contributions made by many
* individuals on behalf of the Apache Software Foundation. For more
* information on the Apache Software Foundation, please see
* <http://www.apache.org/>.
*
*/
/**
* Client specific HTTP entity implementations.
*/
package org.apache.http.client.entity;

View File

@ -1,131 +0,0 @@
/*
* ====================================================================
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you under the Apache License, Version 2.0 (the
* "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
* KIND, either express or implied. See the License for the
* specific language governing permissions and limitations
* under the License.
* ====================================================================
*
* This software consists of voluntary contributions made by many
* individuals on behalf of the Apache Software Foundation. For more
* information on the Apache Software Foundation, please see
* <http://www.apache.org/>.
*
*/
package org.apache.http.client.methods;
import java.io.IOException;
import java.util.concurrent.atomic.AtomicBoolean;
import java.util.concurrent.atomic.AtomicReference;
import org.apache.http.HttpRequest;
import org.apache.http.client.utils.CloneUtilsHC4;
import org.apache.http.concurrent.Cancellable;
import org.apache.http.conn.ClientConnectionRequest;
import org.apache.http.conn.ConnectionReleaseTrigger;
import org.apache.http.message.AbstractHttpMessage;
@SuppressWarnings("deprecation")
public abstract class AbstractExecutionAwareRequest extends AbstractHttpMessage implements
HttpExecutionAware, AbortableHttpRequest, Cloneable, HttpRequest {
private final AtomicBoolean aborted;
private final AtomicReference<Cancellable> cancellableRef;
protected AbstractExecutionAwareRequest() {
super();
this.aborted = new AtomicBoolean(false);
this.cancellableRef = new AtomicReference<Cancellable>(null);
}
@Deprecated
public void setConnectionRequest(final ClientConnectionRequest connRequest) {
setCancellable(new Cancellable() {
public boolean cancel() {
connRequest.abortRequest();
return true;
}
});
}
@Deprecated
public void setReleaseTrigger(final ConnectionReleaseTrigger releaseTrigger) {
setCancellable(new Cancellable() {
public boolean cancel() {
try {
releaseTrigger.abortConnection();
return true;
} catch (final IOException ex) {
return false;
}
}
});
}
public void abort() {
if (this.aborted.compareAndSet(false, true)) {
final Cancellable cancellable = this.cancellableRef.getAndSet(null);
if (cancellable != null) {
cancellable.cancel();
}
}
}
public boolean isAborted() {
return this.aborted.get();
}
/**
* @since 4.2
*/
public void setCancellable(final Cancellable cancellable) {
if (!this.aborted.get()) {
this.cancellableRef.set(cancellable);
}
}
@Override
public Object clone() throws CloneNotSupportedException {
final AbstractExecutionAwareRequest clone = (AbstractExecutionAwareRequest) super.clone();
clone.headergroup = CloneUtilsHC4.cloneObject(this.headergroup);
clone.params = CloneUtilsHC4.cloneObject(this.params);
return clone;
}
/**
* @since 4.2
*/
public void completed() {
this.cancellableRef.set(null);
}
/**
* Resets internal state of the request making it reusable.
*
* @since 4.2
*/
public void reset() {
final Cancellable cancellable = this.cancellableRef.getAndSet(null);
if (cancellable != null) {
cancellable.cancel();
}
this.aborted.set(false);
}
}

View File

@ -1,40 +0,0 @@
/*
* ====================================================================
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you under the Apache License, Version 2.0 (the
* "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
* KIND, either express or implied. See the License for the
* specific language governing permissions and limitations
* under the License.
* ====================================================================
*
* This software consists of voluntary contributions made by many
* individuals on behalf of the Apache Software Foundation. For more
* information on the Apache Software Foundation, please see
* <http://www.apache.org/>.
*
*/
package org.apache.http.client.methods;
import java.io.Closeable;
import org.apache.http.HttpResponse;
/**
* Extended version of the {@link HttpResponse} interface that also extends {@link Closeable}.
*
* @since 4.3
*/
public interface CloseableHttpResponse extends HttpResponse, Closeable {
}

View File

@ -1,44 +0,0 @@
/*
* ====================================================================
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you under the Apache License, Version 2.0 (the
* "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
* KIND, either express or implied. See the License for the
* specific language governing permissions and limitations
* under the License.
* ====================================================================
*
* This software consists of voluntary contributions made by many
* individuals on behalf of the Apache Software Foundation. For more
* information on the Apache Software Foundation, please see
* <http://www.apache.org/>.
*
*/
package org.apache.http.client.methods;
import org.apache.http.client.config.RequestConfig;
/**
* Configuration interface for HTTP requests.
*
* @since 4.3
*/
public interface Configurable {
/**
* Returns actual request configuration.
*/
RequestConfig getConfig();
}

View File

@ -1,77 +0,0 @@
/*
* ====================================================================
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you under the Apache License, Version 2.0 (the
* "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
* KIND, either express or implied. See the License for the
* specific language governing permissions and limitations
* under the License.
* ====================================================================
*
* This software consists of voluntary contributions made by many
* individuals on behalf of the Apache Software Foundation. For more
* information on the Apache Software Foundation, please see
* <http://www.apache.org/>.
*
*/
package org.apache.http.client.methods;
import java.net.URI;
import org.apache.http.annotation.NotThreadSafe;
/**
* HTTP DELETE method
* <p>
* The HTTP DELETE method is defined in section 9.7 of
* <a href="http://www.ietf.org/rfc/rfc2616.txt">RFC2616</a>:
* <blockquote>
* The DELETE method requests that the origin server delete the resource
* identified by the Request-URI. [...] The client cannot
* be guaranteed that the operation has been carried out, even if the
* status code returned from the origin server indicates that the action
* has been completed successfully.
* </blockquote>
*
* @since 4.0
*/
@NotThreadSafe // HttpRequestBaseHC4 is @NotThreadSafe
public class HttpDeleteHC4 extends HttpRequestBaseHC4 {
public final static String METHOD_NAME = "DELETE";
public HttpDeleteHC4() {
super();
}
public HttpDeleteHC4(final URI uri) {
super();
setURI(uri);
}
/**
* @throws IllegalArgumentException if the uri is invalid.
*/
public HttpDeleteHC4(final String uri) {
super();
setURI(URI.create(uri));
}
@Override
public String getMethod() {
return METHOD_NAME;
}
}

View File

@ -1,76 +0,0 @@
/*
* ====================================================================
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you under the Apache License, Version 2.0 (the
* "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
* KIND, either express or implied. See the License for the
* specific language governing permissions and limitations
* under the License.
* ====================================================================
*
* This software consists of voluntary contributions made by many
* individuals on behalf of the Apache Software Foundation. For more
* information on the Apache Software Foundation, please see
* <http://www.apache.org/>.
*
*/
package org.apache.http.client.methods;
import org.apache.http.Header;
import org.apache.http.HttpEntity;
import org.apache.http.HttpEntityEnclosingRequest;
import org.apache.http.annotation.NotThreadSafe;
import org.apache.http.client.utils.CloneUtilsHC4;
import org.apache.http.protocol.HTTP;
/**
* Basic implementation of an entity enclosing HTTP request
* that can be modified
*
* @since 4.0
*/
@NotThreadSafe // HttpRequestBaseHC4 is @NotThreadSafe
public abstract class HttpEntityEnclosingRequestBaseHC4
extends HttpRequestBaseHC4 implements HttpEntityEnclosingRequest {
private HttpEntity entity;
public HttpEntityEnclosingRequestBaseHC4() {
super();
}
public HttpEntity getEntity() {
return this.entity;
}
public void setEntity(final HttpEntity entity) {
this.entity = entity;
}
public boolean expectContinue() {
final Header expect = getFirstHeader(HTTP.EXPECT_DIRECTIVE);
return expect != null && HTTP.EXPECT_CONTINUE.equalsIgnoreCase(expect.getValue());
}
@Override
public Object clone() throws CloneNotSupportedException {
final HttpEntityEnclosingRequestBaseHC4 clone =
(HttpEntityEnclosingRequestBaseHC4) super.clone();
if (this.entity != null) {
clone.entity = CloneUtilsHC4.cloneObject(this.entity);
}
return clone;
}
}

View File

@ -1,48 +0,0 @@
/*
* ====================================================================
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you under the Apache License, Version 2.0 (the
* "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
* KIND, either express or implied. See the License for the
* specific language governing permissions and limitations
* under the License.
* ====================================================================
*
* This software consists of voluntary contributions made by many
* individuals on behalf of the Apache Software Foundation. For more
* information on the Apache Software Foundation, please see
* <http://www.apache.org/>.
*
*/
package org.apache.http.client.methods;
import org.apache.http.concurrent.Cancellable;
/**
* Interface to be implemented by any object that wishes to be notified of
* blocking I/O operations that could be cancelled.
*
* @since 4.3
*/
public interface HttpExecutionAware {
boolean isAborted();
/**
* Sets {@link Cancellable} for the ongoing operation.
*/
void setCancellable(Cancellable cancellable);
}

View File

@ -1,77 +0,0 @@
/*
* ====================================================================
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you under the Apache License, Version 2.0 (the
* "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
* KIND, either express or implied. See the License for the
* specific language governing permissions and limitations
* under the License.
* ====================================================================
*
* This software consists of voluntary contributions made by many
* individuals on behalf of the Apache Software Foundation. For more
* information on the Apache Software Foundation, please see
* <http://www.apache.org/>.
*
*/
package org.apache.http.client.methods;
import java.net.URI;
import org.apache.http.annotation.NotThreadSafe;
/**
* HTTP GET method.
* <p>
* The HTTP GET method is defined in section 9.3 of
* <a href="http://www.ietf.org/rfc/rfc2616.txt">RFC2616</a>:
* <blockquote>
* The GET method means retrieve whatever information (in the form of an
* entity) is identified by the Request-URI. If the Request-URI refers
* to a data-producing process, it is the produced data which shall be
* returned as the entity in the response and not the source text of the
* process, unless that text happens to be the output of the process.
* </blockquote>
* </p>
*
* @since 4.0
*/
@NotThreadSafe
public class HttpGetHC4 extends HttpRequestBaseHC4 {
public final static String METHOD_NAME = "GET";
public HttpGetHC4() {
super();
}
public HttpGetHC4(final URI uri) {
super();
setURI(uri);
}
/**
* @throws IllegalArgumentException if the uri is invalid.
*/
public HttpGetHC4(final String uri) {
super();
setURI(URI.create(uri));
}
@Override
public String getMethod() {
return METHOD_NAME;
}
}

View File

@ -1,80 +0,0 @@
/*
* ====================================================================
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you under the Apache License, Version 2.0 (the
* "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
* KIND, either express or implied. See the License for the
* specific language governing permissions and limitations
* under the License.
* ====================================================================
*
* This software consists of voluntary contributions made by many
* individuals on behalf of the Apache Software Foundation. For more
* information on the Apache Software Foundation, please see
* <http://www.apache.org/>.
*
*/
package org.apache.http.client.methods;
import java.net.URI;
import org.apache.http.annotation.NotThreadSafe;
/**
* HTTP HEAD method.
* <p>
* The HTTP HEAD method is defined in section 9.4 of
* <a href="http://www.ietf.org/rfc/rfc2616.txt">RFC2616</a>:
* <blockquote>
* The HEAD method is identical to GET except that the server MUST NOT
* return a message-body in the response. The metainformation contained
* in the HTTP headers in response to a HEAD request SHOULD be identical
* to the information sent in response to a GET request. This method can
* be used for obtaining metainformation about the entity implied by the
* request without transferring the entity-body itself. This method is
* often used for testing hypertext links for validity, accessibility,
* and recent modification.
* </blockquote>
* </p>
*
* @since 4.0
*/
@NotThreadSafe
public class HttpHeadHC4 extends HttpRequestBaseHC4 {
public final static String METHOD_NAME = "HEAD";
public HttpHeadHC4() {
super();
}
public HttpHeadHC4(final URI uri) {
super();
setURI(uri);
}
/**
* @throws IllegalArgumentException if the uri is invalid.
*/
public HttpHeadHC4(final String uri) {
super();
setURI(URI.create(uri));
}
@Override
public String getMethod() {
return METHOD_NAME;
}
}

View File

@ -1,100 +0,0 @@
/*
* ====================================================================
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you under the Apache License, Version 2.0 (the
* "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
* KIND, either express or implied. See the License for the
* specific language governing permissions and limitations
* under the License.
* ====================================================================
*
* This software consists of voluntary contributions made by many
* individuals on behalf of the Apache Software Foundation. For more
* information on the Apache Software Foundation, please see
* <http://www.apache.org/>.
*
*/
package org.apache.http.client.methods;
import java.net.URI;
import java.util.HashSet;
import java.util.Set;
import org.apache.http.Header;
import org.apache.http.HeaderElement;
import org.apache.http.HeaderIterator;
import org.apache.http.HttpResponse;
import org.apache.http.annotation.NotThreadSafe;
import org.apache.http.util.Args;
/**
* HTTP OPTIONS method.
* <p>
* The HTTP OPTIONS method is defined in section 9.2 of
* <a href="http://www.ietf.org/rfc/rfc2616.txt">RFC2616</a>:
* <blockquote>
* The OPTIONS method represents a request for information about the
* communication options available on the request/response chain
* identified by the Request-URI. This method allows the client to
* determine the options and/or requirements associated with a resource,
* or the capabilities of a server, without implying a resource action
* or initiating a resource retrieval.
* </blockquote>
* </p>
*
* @since 4.0
*/
@NotThreadSafe
public class HttpOptionsHC4 extends HttpRequestBaseHC4 {
public final static String METHOD_NAME = "OPTIONS";
public HttpOptionsHC4() {
super();
}
public HttpOptionsHC4(final URI uri) {
super();
setURI(uri);
}
/**
* @throws IllegalArgumentException if the uri is invalid.
*/
public HttpOptionsHC4(final String uri) {
super();
setURI(URI.create(uri));
}
@Override
public String getMethod() {
return METHOD_NAME;
}
public Set<String> getAllowedMethods(final HttpResponse response) {
Args.notNull(response, "HTTP response");
final HeaderIterator it = response.headerIterator("Allow");
final Set<String> methods = new HashSet<String>();
while (it.hasNext()) {
final Header header = it.nextHeader();
final HeaderElement[] elements = header.getElements();
for (final HeaderElement element : elements) {
methods.add(element.getName());
}
}
return methods;
}
}

View File

@ -1,75 +0,0 @@
/*
* ====================================================================
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you under the Apache License, Version 2.0 (the
* "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
* KIND, either express or implied. See the License for the
* specific language governing permissions and limitations
* under the License.
* ====================================================================
*
* This software consists of voluntary contributions made by many
* individuals on behalf of the Apache Software Foundation. For more
* information on the Apache Software Foundation, please see
* <http://www.apache.org/>.
*
*/
package org.apache.http.client.methods;
import java.net.URI;
import org.apache.http.annotation.NotThreadSafe;
/**
* HTTP PATCH method.
* <p>
* The HTTP PATCH method is defined in <a
* href="http://tools.ietf.org/html/rfc5789">RF5789</a>: <blockquote> The PATCH
* method requests that a set of changes described in the request entity be
* applied to the resource identified by the Request- URI. Differs from the PUT
* method in the way the server processes the enclosed entity to modify the
* resource identified by the Request-URI. In a PUT request, the enclosed entity
* origin server, and the client is requesting that the stored version be
* replaced. With PATCH, however, the enclosed entity contains a set of
* instructions describing how a resource currently residing on the origin
* server should be modified to produce a new version. </blockquote>
* </p>
*
* @since 4.2
*/
@NotThreadSafe
public class HttpPatch extends HttpEntityEnclosingRequestBaseHC4 {
public final static String METHOD_NAME = "PATCH";
public HttpPatch() {
super();
}
public HttpPatch(final URI uri) {
super();
setURI(uri);
}
public HttpPatch(final String uri) {
super();
setURI(URI.create(uri));
}
@Override
public String getMethod() {
return METHOD_NAME;
}
}

View File

@ -1,84 +0,0 @@
/*
* ====================================================================
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you under the Apache License, Version 2.0 (the
* "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
* KIND, either express or implied. See the License for the
* specific language governing permissions and limitations
* under the License.
* ====================================================================
*
* This software consists of voluntary contributions made by many
* individuals on behalf of the Apache Software Foundation. For more
* information on the Apache Software Foundation, please see
* <http://www.apache.org/>.
*
*/
package org.apache.http.client.methods;
import java.net.URI;
import org.apache.http.annotation.NotThreadSafe;
/**
* HTTP POST method.
* <p>
* The HTTP POST method is defined in section 9.5 of
* <a href="http://www.ietf.org/rfc/rfc2616.txt">RFC2616</a>:
* <blockquote>
* The POST method is used to request that the origin server accept the entity
* enclosed in the request as a new subordinate of the resource identified by
* the Request-URI in the Request-Line. POST is designed to allow a uniform
* method to cover the following functions:
* <ul>
* <li>Annotation of existing resources</li>
* <li>Posting a message to a bulletin board, newsgroup, mailing list, or
* similar group of articles</li>
* <li>Providing a block of data, such as the result of submitting a form,
* to a data-handling process</li>
* <li>Extending a database through an append operation</li>
* </ul>
* </blockquote>
* </p>
*
* @since 4.0
*/
@NotThreadSafe
public class HttpPostHC4 extends HttpEntityEnclosingRequestBaseHC4 {
public final static String METHOD_NAME = "POST";
public HttpPostHC4() {
super();
}
public HttpPostHC4(final URI uri) {
super();
setURI(uri);
}
/**
* @throws IllegalArgumentException if the uri is invalid.
*/
public HttpPostHC4(final String uri) {
super();
setURI(URI.create(uri));
}
@Override
public String getMethod() {
return METHOD_NAME;
}
}

View File

@ -1,76 +0,0 @@
/*
* ====================================================================
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you under the Apache License, Version 2.0 (the
* "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
* KIND, either express or implied. See the License for the
* specific language governing permissions and limitations
* under the License.
* ====================================================================
*
* This software consists of voluntary contributions made by many
* individuals on behalf of the Apache Software Foundation. For more
* information on the Apache Software Foundation, please see
* <http://www.apache.org/>.
*
*/
package org.apache.http.client.methods;
import java.net.URI;
import org.apache.http.annotation.NotThreadSafe;
/**
* HTTP PUT method.
* <p>
* The HTTP PUT method is defined in section 9.6 of
* <a href="http://www.ietf.org/rfc/rfc2616.txt">RFC2616</a>:
* <blockquote>
* The PUT method requests that the enclosed entity be stored under the
* supplied Request-URI. If the Request-URI refers to an already
* existing resource, the enclosed entity SHOULD be considered as a
* modified version of the one residing on the origin server.
* </blockquote>
* </p>
*
* @since 4.0
*/
@NotThreadSafe
public class HttpPutHC4 extends HttpEntityEnclosingRequestBaseHC4 {
public final static String METHOD_NAME = "PUT";
public HttpPutHC4() {
super();
}
public HttpPutHC4(final URI uri) {
super();
setURI(uri);
}
/**
* @throws IllegalArgumentException if the uri is invalid.
*/
public HttpPutHC4(final String uri) {
super();
setURI(URI.create(uri));
}
@Override
public String getMethod() {
return METHOD_NAME;
}
}

View File

@ -1,124 +0,0 @@
/*
* ====================================================================
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you under the Apache License, Version 2.0 (the
* "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
* KIND, either express or implied. See the License for the
* specific language governing permissions and limitations
* under the License.
* ====================================================================
*
* This software consists of voluntary contributions made by many
* individuals on behalf of the Apache Software Foundation. For more
* information on the Apache Software Foundation, please see
* <http://www.apache.org/>.
*
*/
package org.apache.http.client.methods;
import java.net.URI;
import org.apache.http.ProtocolVersion;
import org.apache.http.RequestLine;
import org.apache.http.annotation.NotThreadSafe;
import org.apache.http.client.config.RequestConfig;
import org.apache.http.message.BasicRequestLine;
import org.apache.http.params.HttpProtocolParams;
/**
* Base implementation of {@link HttpUriRequest}.
*
* @since 4.0
*/
@SuppressWarnings("deprecation")
@NotThreadSafe
public abstract class HttpRequestBaseHC4 extends AbstractExecutionAwareRequest
implements HttpUriRequest, Configurable {
private ProtocolVersion version;
private URI uri;
private RequestConfig config;
public abstract String getMethod();
/**
* @since 4.3
*/
public void setProtocolVersion(final ProtocolVersion version) {
this.version = version;
}
public ProtocolVersion getProtocolVersion() {
return version != null ? version : HttpProtocolParams.getVersion(getParams());
}
/**
* Returns the original request URI.
* <p>
* Please note URI remains unchanged in the course of request execution and
* is not updated if the request is redirected to another location.
*/
public URI getURI() {
return this.uri;
}
public RequestLine getRequestLine() {
final String method = getMethod();
final ProtocolVersion ver = getProtocolVersion();
final URI uri = getURI();
String uritext = null;
if (uri != null) {
uritext = uri.toASCIIString();
}
if (uritext == null || uritext.length() == 0) {
uritext = "/";
}
return new BasicRequestLine(method, uritext, ver);
}
public RequestConfig getConfig() {
return config;
}
public void setConfig(final RequestConfig config) {
this.config = config;
}
public void setURI(final URI uri) {
this.uri = uri;
}
/**
* @since 4.2
*/
public void started() {
}
/**
* A convenience method to simplify migration from HttpClient 3.1 API. This method is
* equivalent to {@link #reset()}.
*
* @since 4.2
*/
public void releaseConnection() {
reset();
}
@Override
public String toString() {
return getMethod() + " " + getURI() + " " + getProtocolVersion();
}
}

View File

@ -1,171 +0,0 @@
/*
* ====================================================================
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you under the Apache License, Version 2.0 (the
* "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
* KIND, either express or implied. See the License for the
* specific language governing permissions and limitations
* under the License.
* ====================================================================
*
* This software consists of voluntary contributions made by many
* individuals on behalf of the Apache Software Foundation. For more
* information on the Apache Software Foundation, please see
* <http://www.apache.org/>.
*
*/
package org.apache.http.client.methods;
import java.net.URI;
import org.apache.http.Header;
import org.apache.http.HttpEntity;
import org.apache.http.HttpEntityEnclosingRequest;
import org.apache.http.HttpRequest;
import org.apache.http.ProtocolVersion;
import org.apache.http.RequestLine;
import org.apache.http.annotation.NotThreadSafe;
import org.apache.http.message.AbstractHttpMessage;
import org.apache.http.message.BasicRequestLine;
import org.apache.http.params.HttpParams;
import org.apache.http.protocol.HTTP;
/**
* A wrapper class for {@link HttpRequest} that can be used to change properties of the current
* request without modifying the original object.
*
* @since 4.3
*/
@SuppressWarnings("deprecation")
@NotThreadSafe
public class HttpRequestWrapper extends AbstractHttpMessage implements HttpUriRequest {
private final HttpRequest original;
private final String method;
private ProtocolVersion version;
private URI uri;
private HttpRequestWrapper(final HttpRequest request) {
super();
this.original = request;
this.version = this.original.getRequestLine().getProtocolVersion();
this.method = this.original.getRequestLine().getMethod();
if (request instanceof HttpUriRequest) {
this.uri = ((HttpUriRequest) request).getURI();
} else {
this.uri = null;
}
setHeaders(request.getAllHeaders());
}
public ProtocolVersion getProtocolVersion() {
return this.version != null ? this.version : this.original.getProtocolVersion();
}
public void setProtocolVersion(final ProtocolVersion version) {
this.version = version;
}
public URI getURI() {
return this.uri;
}
public void setURI(final URI uri) {
this.uri = uri;
}
public String getMethod() {
return method;
}
public void abort() throws UnsupportedOperationException {
throw new UnsupportedOperationException();
}
public boolean isAborted() {
return false;
}
public RequestLine getRequestLine() {
String requestUri = null;
if (this.uri != null) {
requestUri = this.uri.toASCIIString();
} else {
requestUri = this.original.getRequestLine().getUri();
}
if (requestUri == null || requestUri.length() == 0) {
requestUri = "/";
}
return new BasicRequestLine(this.method, requestUri, getProtocolVersion());
}
public HttpRequest getOriginal() {
return this.original;
}
@Override
public String toString() {
return getRequestLine() + " " + this.headergroup;
}
static class HttpEntityEnclosingRequestWrapper extends HttpRequestWrapper
implements HttpEntityEnclosingRequest {
private HttpEntity entity;
public HttpEntityEnclosingRequestWrapper(final HttpEntityEnclosingRequest request) {
super(request);
this.entity = request.getEntity();
}
public HttpEntity getEntity() {
return this.entity;
}
public void setEntity(final HttpEntity entity) {
this.entity = entity;
}
public boolean expectContinue() {
final Header expect = getFirstHeader(HTTP.EXPECT_DIRECTIVE);
return expect != null && HTTP.EXPECT_CONTINUE.equalsIgnoreCase(expect.getValue());
}
}
public static HttpRequestWrapper wrap(final HttpRequest request) {
if (request == null) {
return null;
}
if (request instanceof HttpEntityEnclosingRequest) {
return new HttpEntityEnclosingRequestWrapper((HttpEntityEnclosingRequest) request);
} else {
return new HttpRequestWrapper(request);
}
}
/**
* @deprecated (4.3) use
* {@link org.apache.http.client.config.RequestConfig}.
*/
@Override
@Deprecated
public HttpParams getParams() {
if (this.params == null) {
this.params = original.getParams().copy();
}
return this.params;
}
}

View File

@ -1,79 +0,0 @@
/*
* ====================================================================
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you under the Apache License, Version 2.0 (the
* "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
* KIND, either express or implied. See the License for the
* specific language governing permissions and limitations
* under the License.
* ====================================================================
*
* This software consists of voluntary contributions made by many
* individuals on behalf of the Apache Software Foundation. For more
* information on the Apache Software Foundation, please see
* <http://www.apache.org/>.
*
*/
package org.apache.http.client.methods;
import java.net.URI;
import org.apache.http.annotation.NotThreadSafe;
/**
* HTTP TRACE method.
* <p>
* The HTTP TRACE method is defined in section 9.6 of
* <a href="http://www.ietf.org/rfc/rfc2616.txt">RFC2616</a>:
* <blockquote>
* The TRACE method is used to invoke a remote, application-layer loop-
* back of the request message. The final recipient of the request
* SHOULD reflect the message received back to the client as the
* entity-body of a 200 (OK) response. The final recipient is either the
* origin server or the first proxy or gateway to receive a Max-Forwards
* value of zero (0) in the request (see section 14.31). A TRACE request
* MUST NOT include an entity.
* </blockquote>
* </p>
*
* @since 4.0
*/
@NotThreadSafe
public class HttpTraceHC4 extends HttpRequestBaseHC4 {
public final static String METHOD_NAME = "TRACE";
public HttpTraceHC4() {
super();
}
public HttpTraceHC4(final URI uri) {
super();
setURI(uri);
}
/**
* @throws IllegalArgumentException if the uri is invalid.
*/
public HttpTraceHC4(final String uri) {
super();
setURI(URI.create(uri));
}
@Override
public String getMethod() {
return METHOD_NAME;
}
}

View File

@ -1,352 +0,0 @@
/*
* ====================================================================
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you under the Apache License, Version 2.0 (the
* "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
* KIND, either express or implied. See the License for the
* specific language governing permissions and limitations
* under the License.
* ====================================================================
*
* This software consists of voluntary contributions made by many
* individuals on behalf of the Apache Software Foundation. For more
* information on the Apache Software Foundation, please see
* <http://www.apache.org/>.
*
*/
package org.apache.http.client.methods;
import java.net.URI;
import java.net.URISyntaxException;
import java.nio.charset.Charset;
import java.util.ArrayList;
import java.util.LinkedList;
import java.util.List;
import org.apache.http.Header;
import org.apache.http.HeaderIterator;
import org.apache.http.HttpEntity;
import org.apache.http.HttpEntityEnclosingRequest;
import org.apache.http.HttpRequest;
import org.apache.http.NameValuePair;
import org.apache.http.ProtocolVersion;
import org.apache.http.annotation.NotThreadSafe;
import org.apache.http.client.config.RequestConfig;
import org.apache.http.client.entity.UrlEncodedFormEntityHC4;
import org.apache.http.client.utils.URIBuilder;
import org.apache.http.message.BasicHeader;
import org.apache.http.message.BasicNameValuePair;
import org.apache.http.message.HeaderGroup;
import org.apache.http.protocol.HTTP;
import org.apache.http.util.Args;
/**
* Builder for {@link HttpUriRequest} instances.
* <p/>
* Please note that this class treats parameters differently depending on composition
* of the request: if the request has a content entity explicitly set with
* {@link #setEntity(org.apache.http.HttpEntity)} or it is not an entity enclosing method
* (such as POST or PUT), parameters will be added to the query component of the request URI.
* Otherwise, parameters will be added as a URL encoded {@link UrlEncodedFormEntityHC4 entity}.
*
* @since 4.3
*/
@NotThreadSafe
public class RequestBuilder {
private String method;
private ProtocolVersion version;
private URI uri;
private HeaderGroup headergroup;
private HttpEntity entity;
private LinkedList<NameValuePair> parameters;
private RequestConfig config;
RequestBuilder(final String method) {
super();
this.method = method;
}
RequestBuilder() {
this(null);
}
public static RequestBuilder create(final String method) {
Args.notBlank(method, "HTTP method");
return new RequestBuilder(method);
}
public static RequestBuilder get() {
return new RequestBuilder(HttpGetHC4.METHOD_NAME);
}
public static RequestBuilder head() {
return new RequestBuilder(HttpHeadHC4.METHOD_NAME);
}
public static RequestBuilder post() {
return new RequestBuilder(HttpPostHC4.METHOD_NAME);
}
public static RequestBuilder put() {
return new RequestBuilder(HttpPutHC4.METHOD_NAME);
}
public static RequestBuilder delete() {
return new RequestBuilder(HttpDeleteHC4.METHOD_NAME);
}
public static RequestBuilder trace() {
return new RequestBuilder(HttpTraceHC4.METHOD_NAME);
}
public static RequestBuilder options() {
return new RequestBuilder(HttpOptionsHC4.METHOD_NAME);
}
public static RequestBuilder copy(final HttpRequest request) {
Args.notNull(request, "HTTP request");
return new RequestBuilder().doCopy(request);
}
private RequestBuilder doCopy(final HttpRequest request) {
if (request == null) {
return this;
}
method = request.getRequestLine().getMethod();
version = request.getRequestLine().getProtocolVersion();
if (request instanceof HttpUriRequest) {
uri = ((HttpUriRequest) request).getURI();
} else {
uri = URI.create(request.getRequestLine().getUri());
}
if (headergroup == null) {
headergroup = new HeaderGroup();
}
headergroup.clear();
headergroup.setHeaders(request.getAllHeaders());
if (request instanceof HttpEntityEnclosingRequest) {
entity = ((HttpEntityEnclosingRequest) request).getEntity();
} else {
entity = null;
}
if (request instanceof Configurable) {
this.config = ((Configurable) request).getConfig();
} else {
this.config = null;
}
this.parameters = null;
return this;
}
public String getMethod() {
return method;
}
public ProtocolVersion getVersion() {
return version;
}
public RequestBuilder setVersion(final ProtocolVersion version) {
this.version = version;
return this;
}
public URI getUri() {
return uri;
}
public RequestBuilder setUri(final URI uri) {
this.uri = uri;
return this;
}
public RequestBuilder setUri(final String uri) {
this.uri = uri != null ? URI.create(uri) : null;
return this;
}
public Header getFirstHeader(final String name) {
return headergroup != null ? headergroup.getFirstHeader(name) : null;
}
public Header getLastHeader(final String name) {
return headergroup != null ? headergroup.getLastHeader(name) : null;
}
public Header[] getHeaders(final String name) {
return headergroup != null ? headergroup.getHeaders(name) : null;
}
public RequestBuilder addHeader(final Header header) {
if (headergroup == null) {
headergroup = new HeaderGroup();
}
headergroup.addHeader(header);
return this;
}
public RequestBuilder addHeader(final String name, final String value) {
if (headergroup == null) {
headergroup = new HeaderGroup();
}
this.headergroup.addHeader(new BasicHeader(name, value));
return this;
}
public RequestBuilder removeHeader(final Header header) {
if (headergroup == null) {
headergroup = new HeaderGroup();
}
headergroup.removeHeader(header);
return this;
}
public RequestBuilder removeHeaders(final String name) {
if (name == null || headergroup == null) {
return this;
}
for (final HeaderIterator i = headergroup.iterator(); i.hasNext(); ) {
final Header header = i.nextHeader();
if (name.equalsIgnoreCase(header.getName())) {
i.remove();
}
}
return this;
}
public RequestBuilder setHeader(final Header header) {
if (headergroup == null) {
headergroup = new HeaderGroup();
}
this.headergroup.updateHeader(header);
return this;
}
public RequestBuilder setHeader(final String name, final String value) {
if (headergroup == null) {
headergroup = new HeaderGroup();
}
this.headergroup.updateHeader(new BasicHeader(name, value));
return this;
}
public HttpEntity getEntity() {
return entity;
}
public RequestBuilder setEntity(final HttpEntity entity) {
this.entity = entity;
return this;
}
public List<NameValuePair> getParameters() {
return parameters != null ? new ArrayList<NameValuePair>(parameters) :
new ArrayList<NameValuePair>();
}
public RequestBuilder addParameter(final NameValuePair nvp) {
Args.notNull(nvp, "Name value pair");
if (parameters == null) {
parameters = new LinkedList<NameValuePair>();
}
parameters.add(nvp);
return this;
}
public RequestBuilder addParameter(final String name, final String value) {
return addParameter(new BasicNameValuePair(name, value));
}
public RequestBuilder addParameters(final NameValuePair... nvps) {
for (final NameValuePair nvp: nvps) {
addParameter(nvp);
}
return this;
}
public RequestConfig getConfig() {
return config;
}
public RequestBuilder setConfig(final RequestConfig config) {
this.config = config;
return this;
}
public HttpUriRequest build() {
final HttpRequestBaseHC4 result;
URI uri = this.uri != null ? this.uri : URI.create("/");
HttpEntity entity = this.entity;
if (parameters != null && !parameters.isEmpty()) {
if (entity == null && (HttpPostHC4.METHOD_NAME.equalsIgnoreCase(method)
|| HttpPutHC4.METHOD_NAME.equalsIgnoreCase(method))) {
entity = new UrlEncodedFormEntityHC4(parameters, Charset.forName(HTTP.DEFAULT_CONTENT_CHARSET));
} else {
try {
uri = new URIBuilder(uri).addParameters(parameters).build();
} catch (final URISyntaxException ex) {
// should never happen
}
}
}
if (entity == null) {
result = new InternalRequest(method);
} else {
final InternalEntityEclosingRequest request = new InternalEntityEclosingRequest(method);
request.setEntity(entity);
result = request;
}
result.setProtocolVersion(this.version);
result.setURI(uri);
if (this.headergroup != null) {
result.setHeaders(this.headergroup.getAllHeaders());
}
result.setConfig(this.config);
return result;
}
static class InternalRequest extends HttpRequestBaseHC4 {
private final String method;
InternalRequest(final String method) {
super();
this.method = method;
}
@Override
public String getMethod() {
return this.method;
}
}
static class InternalEntityEclosingRequest extends HttpEntityEnclosingRequestBaseHC4 {
private final String method;
InternalEntityEclosingRequest(final String method) {
super();
this.method = method;
}
@Override
public String getMethod() {
return this.method;
}
}
}

View File

@ -1,31 +0,0 @@
/*
* ====================================================================
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you under the Apache License, Version 2.0 (the
* "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
* KIND, either express or implied. See the License for the
* specific language governing permissions and limitations
* under the License.
* ====================================================================
*
* This software consists of voluntary contributions made by many
* individuals on behalf of the Apache Software Foundation. For more
* information on the Apache Software Foundation, please see
* <http://www.apache.org/>.
*
*/
/**
* Standard HTTP method implementations.
*/
package org.apache.http.client.methods;

View File

@ -1,31 +0,0 @@
/*
* ====================================================================
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you under the Apache License, Version 2.0 (the
* "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
* KIND, either express or implied. See the License for the
* specific language governing permissions and limitations
* under the License.
* ====================================================================
*
* This software consists of voluntary contributions made by many
* individuals on behalf of the Apache Software Foundation. For more
* information on the Apache Software Foundation, please see
* <http://www.apache.org/>.
*
*/
/**
* Client HTTP communication APIs.
*/
package org.apache.http.client;

View File

@ -1,95 +0,0 @@
/*
* ====================================================================
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you under the Apache License, Version 2.0 (the
* "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
* KIND, either express or implied. See the License for the
* specific language governing permissions and limitations
* under the License.
* ====================================================================
*
* This software consists of voluntary contributions made by many
* individuals on behalf of the Apache Software Foundation. For more
* information on the Apache Software Foundation, please see
* <http://www.apache.org/>.
*
*/
package org.apache.http.client.params;
import java.lang.reflect.Field;
import java.lang.reflect.Method;
import java.net.InetAddress;
import java.util.Map;
import org.apache.http.HttpHost;
import org.apache.http.client.config.RequestConfig;
import org.apache.http.conn.params.ConnRoutePNames;
import org.apache.http.params.CoreConnectionPNames;
import org.apache.http.params.CoreProtocolPNames;
import org.apache.http.params.HttpParams;
/**
* @deprecated (4.3) provided for compatibility with {@link HttpParams}. Do not use.
*
* @since 4.3
*/
@Deprecated
public final class HttpClientParamConfig {
private HttpClientParamConfig() {
}
@SuppressWarnings("unchecked")
public static RequestConfig getRequestConfig(final HttpParams params) {
if (params == null) {
return null;
}
try {
final Field f = params.getClass().getDeclaredField("parameters");
f.setAccessible(true);
final Map<?, ?> map = (Map<?, ?>) f.get(params);
if (map == null || map.isEmpty()) {
return null;
}
} catch (Exception ignore) {
}
return RequestConfig.custom()
.setSocketTimeout(params.getIntParameter(
CoreConnectionPNames.SO_TIMEOUT, 0))
.setStaleConnectionCheckEnabled(params.getBooleanParameter(
CoreConnectionPNames.STALE_CONNECTION_CHECK, true))
.setConnectTimeout(params.getIntParameter(
CoreConnectionPNames.CONNECTION_TIMEOUT, 0))
.setExpectContinueEnabled(params.getBooleanParameter(
CoreProtocolPNames.USE_EXPECT_CONTINUE, false))
.setProxy((HttpHost) params.getParameter(
ConnRoutePNames.DEFAULT_PROXY))
.setLocalAddress((InetAddress) params.getParameter(
ConnRoutePNames.LOCAL_ADDRESS))
.setAuthenticationEnabled(params.getBooleanParameter(
ClientPNames.HANDLE_AUTHENTICATION, true))
.setCircularRedirectsAllowed(params.getBooleanParameter(
ClientPNames.ALLOW_CIRCULAR_REDIRECTS, false))
.setCookieSpec((String) params.getParameter(
ClientPNames.COOKIE_POLICY))
.setMaxRedirects(params.getIntParameter(
ClientPNames.MAX_REDIRECTS, 50))
.setRedirectsEnabled(params.getBooleanParameter(
ClientPNames.HANDLE_REDIRECTS, true))
.setRelativeRedirectsAllowed(!params.getBooleanParameter(
ClientPNames.REJECT_RELATIVE_REDIRECT, false))
.build();
}
}

View File

@ -1,32 +0,0 @@
/*
* ====================================================================
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you under the Apache License, Version 2.0 (the
* "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
* KIND, either express or implied. See the License for the
* specific language governing permissions and limitations
* under the License.
* ====================================================================
*
* This software consists of voluntary contributions made by many
* individuals on behalf of the Apache Software Foundation. For more
* information on the Apache Software Foundation, please see
* <http://www.apache.org/>.
*
*/
/**
* Deprecated.
* @deprecated (4.3).
*/
package org.apache.http.client.params;

View File

@ -1,249 +0,0 @@
/*
* ====================================================================
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you under the Apache License, Version 2.0 (the
* "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
* KIND, either express or implied. See the License for the
* specific language governing permissions and limitations
* under the License.
* ====================================================================
*
* This software consists of voluntary contributions made by many
* individuals on behalf of the Apache Software Foundation. For more
* information on the Apache Software Foundation, please see
* <http://www.apache.org/>.
*
*/
package org.apache.http.client.protocol;
import java.net.URI;
import java.util.List;
import org.apache.http.annotation.NotThreadSafe;
import org.apache.http.auth.AuthSchemeProvider;
import org.apache.http.auth.AuthStateHC4;
import org.apache.http.client.AuthCache;
import org.apache.http.client.CookieStore;
import org.apache.http.client.CredentialsProvider;
import org.apache.http.client.config.RequestConfig;
import org.apache.http.config.Lookup;
import org.apache.http.conn.routing.HttpRoute;
import org.apache.http.conn.routing.RouteInfo;
import org.apache.http.cookie.CookieOrigin;
import org.apache.http.cookie.CookieSpec;
import org.apache.http.cookie.CookieSpecProvider;
import org.apache.http.protocol.BasicHttpContextHC4;
import org.apache.http.protocol.HttpContext;
import org.apache.http.protocol.HttpCoreContext;
/**
* Adaptor class that provides convenience type safe setters and getters
* for common {@link HttpContext} attributes used in the course
* of HTTP request execution.
*
* @since 4.3
*/
@NotThreadSafe
public class HttpClientContext extends HttpCoreContext {
/**
* Attribute name of a {@link org.apache.http.conn.routing.RouteInfo}
* object that represents the actual connection route.
*/
public static final String HTTP_ROUTE = "http.route";
/**
* Attribute name of a {@link List} object that represents a collection of all
* redirect locations received in the process of request execution.
*/
public static final String REDIRECT_LOCATIONS = "http.protocol.redirect-locations";
/**
* Attribute name of a {@link org.apache.http.config.Lookup} object that represents
* the actual {@link CookieSpecProvider} registry.
*/
public static final String COOKIESPEC_REGISTRY = "http.cookiespec-registry";
/**
* Attribute name of a {@link org.apache.http.cookie.CookieSpec}
* object that represents the actual cookie specification.
*/
public static final String COOKIE_SPEC = "http.cookie-spec";
/**
* Attribute name of a {@link org.apache.http.cookie.CookieOrigin}
* object that represents the actual details of the origin server.
*/
public static final String COOKIE_ORIGIN = "http.cookie-origin";
/**
* Attribute name of a {@link org.apache.http.client.CookieStore}
* object that represents the actual cookie store.
*/
public static final String COOKIE_STORE = "http.cookie-store";
/**
* Attribute name of a {@link org.apache.http.client.CredentialsProvider}
* object that represents the actual credentials provider.
*/
public static final String CREDS_PROVIDER = "http.auth.credentials-provider";
/**
* Attribute name of a {@link org.apache.http.client.AuthCache} object
* that represents the auth scheme cache.
*/
public static final String AUTH_CACHE = "http.auth.auth-cache";
/**
* Attribute name of a {@link org.apache.http.auth.AuthState}
* object that represents the actual target authentication state.
*/
public static final String TARGET_AUTH_STATE = "http.auth.target-scope";
/**
* Attribute name of a {@link org.apache.http.auth.AuthState}
* object that represents the actual proxy authentication state.
*/
public static final String PROXY_AUTH_STATE = "http.auth.proxy-scope";
/**
* Attribute name of a {@link java.lang.Object} object that represents
* the actual user identity such as user {@link java.security.Principal}.
*/
public static final String USER_TOKEN = "http.user-token";
/**
* Attribute name of a {@link org.apache.http.config.Lookup} object that represents
* the actual {@link AuthSchemeProvider} registry.
*/
public static final String AUTHSCHEME_REGISTRY = "http.authscheme-registry";
/**
* Attribute name of a {@link org.apache.http.client.config.RequestConfig} object that
* represents the actual request configuration.
*/
public static final String REQUEST_CONFIG = "http.request-config";
public static HttpClientContext adapt(final HttpContext context) {
if (context instanceof HttpClientContext) {
return (HttpClientContext) context;
} else {
return new HttpClientContext(context);
}
}
public static HttpClientContext create() {
return new HttpClientContext(new BasicHttpContextHC4());
}
public HttpClientContext(final HttpContext context) {
super(context);
}
public HttpClientContext() {
super();
}
public RouteInfo getHttpRoute() {
return getAttribute(HTTP_ROUTE, HttpRoute.class);
}
@SuppressWarnings("unchecked")
public List<URI> getRedirectLocations() {
return getAttribute(REDIRECT_LOCATIONS, List.class);
}
public CookieStore getCookieStore() {
return getAttribute(COOKIE_STORE, CookieStore.class);
}
public void setCookieStore(final CookieStore cookieStore) {
setAttribute(COOKIE_STORE, cookieStore);
}
public CookieSpec getCookieSpec() {
return getAttribute(COOKIE_SPEC, CookieSpec.class);
}
public CookieOrigin getCookieOrigin() {
return getAttribute(COOKIE_ORIGIN, CookieOrigin.class);
}
@SuppressWarnings("unchecked")
private <T> Lookup<T> getLookup(final String name, final Class<T> clazz) {
return getAttribute(name, Lookup.class);
}
public Lookup<CookieSpecProvider> getCookieSpecRegistry() {
return getLookup(COOKIESPEC_REGISTRY, CookieSpecProvider.class);
}
public void setCookieSpecRegistry(final Lookup<CookieSpecProvider> lookup) {
setAttribute(COOKIESPEC_REGISTRY, lookup);
}
public Lookup<AuthSchemeProvider> getAuthSchemeRegistry() {
return getLookup(AUTHSCHEME_REGISTRY, AuthSchemeProvider.class);
}
public void setAuthSchemeRegistry(final Lookup<AuthSchemeProvider> lookup) {
setAttribute(AUTHSCHEME_REGISTRY, lookup);
}
public CredentialsProvider getCredentialsProvider() {
return getAttribute(CREDS_PROVIDER, CredentialsProvider.class);
}
public void setCredentialsProvider(final CredentialsProvider credentialsProvider) {
setAttribute(CREDS_PROVIDER, credentialsProvider);
}
public AuthCache getAuthCache() {
return getAttribute(AUTH_CACHE, AuthCache.class);
}
public void setAuthCache(final AuthCache authCache) {
setAttribute(AUTH_CACHE, authCache);
}
public AuthStateHC4 getTargetAuthState() {
return getAttribute(TARGET_AUTH_STATE, AuthStateHC4.class);
}
public AuthStateHC4 getProxyAuthState() {
return getAttribute(PROXY_AUTH_STATE, AuthStateHC4.class);
}
public <T> T getUserToken(final Class<T> clazz) {
return getAttribute(USER_TOKEN, clazz);
}
public Object getUserToken() {
return getAttribute(USER_TOKEN);
}
public void setUserToken(final Object obj) {
setAttribute(USER_TOKEN, obj);
}
public RequestConfig getRequestConfig() {
final RequestConfig config = getAttribute(REQUEST_CONFIG, RequestConfig.class);
return config != null ? config : RequestConfig.DEFAULT;
}
public void setRequestConfig(final RequestConfig config) {
setAttribute(REQUEST_CONFIG, config);
}
}

View File

@ -1,62 +0,0 @@
/*
* ====================================================================
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you under the Apache License, Version 2.0 (the
* "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
* KIND, either express or implied. See the License for the
* specific language governing permissions and limitations
* under the License.
* ====================================================================
*
* This software consists of voluntary contributions made by many
* individuals on behalf of the Apache Software Foundation. For more
* information on the Apache Software Foundation, please see
* <http://www.apache.org/>.
*
*/
package org.apache.http.client.protocol;
import java.io.IOException;
import org.apache.http.HttpException;
import org.apache.http.HttpRequest;
import org.apache.http.HttpRequestInterceptor;
import org.apache.http.annotation.Immutable;
import org.apache.http.protocol.HttpContext;
/**
* Class responsible for handling Content Encoding requests in HTTP.
* <p>
* Instances of this class are stateless, therefore they're thread-safe and immutable.
*
* @see "http://www.w3.org/Protocols/rfc2616/rfc2616-sec3.html#sec3.5"
*
* @since 4.1
*/
@Immutable
public class RequestAcceptEncoding implements HttpRequestInterceptor {
/**
* Adds the header {@code "Accept-Encoding: gzip,deflate"} to the request.
*/
public void process(
final HttpRequest request,
final HttpContext context) throws HttpException, IOException {
/* Signal support for Accept-Encoding transfer encodings. */
if (!request.containsHeader("Accept-Encoding")) {
request.addHeader("Accept-Encoding", "gzip,deflate");
}
}
}

View File

@ -1,212 +0,0 @@
/*
* ====================================================================
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you under the Apache License, Version 2.0 (the
* "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
* KIND, either express or implied. See the License for the
* specific language governing permissions and limitations
* under the License.
* ====================================================================
*
* This software consists of voluntary contributions made by many
* individuals on behalf of the Apache Software Foundation. For more
* information on the Apache Software Foundation, please see
* <http://www.apache.org/>.
*
*/
package org.apache.http.client.protocol;
import java.io.IOException;
import java.net.URI;
import java.net.URISyntaxException;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import android.util.Log;
import org.apache.http.Header;
import org.apache.http.HttpException;
import org.apache.http.HttpHost;
import org.apache.http.HttpRequest;
import org.apache.http.HttpRequestInterceptor;
import org.apache.http.annotation.Immutable;
import org.apache.http.client.CookieStore;
import org.apache.http.client.config.CookieSpecs;
import org.apache.http.client.config.RequestConfig;
import org.apache.http.client.methods.HttpUriRequest;
import org.apache.http.config.Lookup;
import org.apache.http.conn.routing.RouteInfo;
import org.apache.http.cookie.Cookie;
import org.apache.http.cookie.CookieOrigin;
import org.apache.http.cookie.CookieSpec;
import org.apache.http.cookie.CookieSpecProvider;
import org.apache.http.cookie.SetCookie2;
import org.apache.http.protocol.HttpContext;
import org.apache.http.util.Args;
import org.apache.http.util.TextUtils;
/**
* Request interceptor that matches cookies available in the current
* {@link CookieStore} to the request being executed and generates
* corresponding <code>Cookie</code> request headers.
*
* @since 4.0
*/
@Immutable
public class RequestAddCookiesHC4 implements HttpRequestInterceptor {
private final static String TAG = "HttpClient";
public RequestAddCookiesHC4() {
super();
}
public void process(final HttpRequest request, final HttpContext context)
throws HttpException, IOException {
Args.notNull(request, "HTTP request");
Args.notNull(context, "HTTP context");
final String method = request.getRequestLine().getMethod();
if (method.equalsIgnoreCase("CONNECT")) {
return;
}
final HttpClientContext clientContext = HttpClientContext.adapt(context);
// Obtain cookie store
final CookieStore cookieStore = clientContext.getCookieStore();
if (cookieStore == null) {
if (Log.isLoggable(TAG, Log.DEBUG)) {
Log.d(TAG, "Cookie store not specified in HTTP context");
}
return;
}
// Obtain the registry of cookie specs
final Lookup<CookieSpecProvider> registry = clientContext.getCookieSpecRegistry();
if (registry == null) {
if (Log.isLoggable(TAG, Log.DEBUG)) {
Log.d(TAG, "CookieSpec registry not specified in HTTP context");
}
return;
}
// Obtain the target host, possibly virtual (required)
final HttpHost targetHost = clientContext.getTargetHost();
if (targetHost == null) {
if (Log.isLoggable(TAG, Log.DEBUG)) {
Log.d(TAG, "Target host not set in the context");
}
return;
}
// Obtain the route (required)
final RouteInfo route = clientContext.getHttpRoute();
if (route == null) {
if (Log.isLoggable(TAG, Log.DEBUG)) {
Log.d(TAG, "Connection route not set in the context");
}
return;
}
final RequestConfig config = clientContext.getRequestConfig();
String policy = config.getCookieSpec();
if (policy == null) {
policy = CookieSpecs.BEST_MATCH;
}
if (Log.isLoggable(TAG, Log.DEBUG)) {
Log.d(TAG, "CookieSpec selected: " + policy);
}
URI requestURI = null;
if (request instanceof HttpUriRequest) {
requestURI = ((HttpUriRequest) request).getURI();
} else {
try {
requestURI = new URI(request.getRequestLine().getUri());
} catch (final URISyntaxException ignore) {
}
}
final String path = requestURI != null ? requestURI.getPath() : null;
final String hostName = targetHost.getHostName();
int port = targetHost.getPort();
if (port < 0) {
port = route.getTargetHost().getPort();
}
final CookieOrigin cookieOrigin = new CookieOrigin(
hostName,
port >= 0 ? port : 0,
!TextUtils.isEmpty(path) ? path : "/",
route.isSecure());
// Get an instance of the selected cookie policy
final CookieSpecProvider provider = registry.lookup(policy);
if (provider == null) {
throw new HttpException("Unsupported cookie policy: " + policy);
}
final CookieSpec cookieSpec = provider.create(clientContext);
// Get all cookies available in the HTTP state
final List<Cookie> cookies = new ArrayList<Cookie>(cookieStore.getCookies());
// Find cookies matching the given origin
final List<Cookie> matchedCookies = new ArrayList<Cookie>();
final Date now = new Date();
for (final Cookie cookie : cookies) {
if (!cookie.isExpired(now)) {
if (cookieSpec.match(cookie, cookieOrigin)) {
if (Log.isLoggable(TAG, Log.DEBUG)) {
Log.d(TAG, "Cookie " + cookie + " match " + cookieOrigin);
}
matchedCookies.add(cookie);
}
} else {
if (Log.isLoggable(TAG, Log.DEBUG)) {
Log.d(TAG, "Cookie " + cookie + " expired");
}
}
}
// Generate Cookie request headers
if (!matchedCookies.isEmpty()) {
final List<Header> headers = cookieSpec.formatCookies(matchedCookies);
for (final Header header : headers) {
request.addHeader(header);
}
}
final int ver = cookieSpec.getVersion();
if (ver > 0) {
boolean needVersionHeader = false;
for (final Cookie cookie : matchedCookies) {
if (ver != cookie.getVersion() || !(cookie instanceof SetCookie2)) {
needVersionHeader = true;
}
}
if (needVersionHeader) {
final Header header = cookieSpec.getVersionHeader();
if (header != null) {
// Advertise cookie version support
request.addHeader(header);
}
}
}
// Stick the CookieSpec and CookieOrigin instances to the HTTP context
// so they could be obtained by the response interceptor
context.setAttribute(HttpClientContext.COOKIE_SPEC, cookieSpec);
context.setAttribute(HttpClientContext.COOKIE_ORIGIN, cookieOrigin);
}
}

View File

@ -1,157 +0,0 @@
/*
* ====================================================================
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you under the Apache License, Version 2.0 (the
* "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
* KIND, either express or implied. See the License for the
* specific language governing permissions and limitations
* under the License.
* ====================================================================
*
* This software consists of voluntary contributions made by many
* individuals on behalf of the Apache Software Foundation. For more
* information on the Apache Software Foundation, please see
* <http://www.apache.org/>.
*
*/
package org.apache.http.client.protocol;
import java.io.IOException;
import android.util.Log;
import org.apache.http.HttpException;
import org.apache.http.HttpHost;
import org.apache.http.HttpRequest;
import org.apache.http.HttpRequestInterceptor;
import org.apache.http.annotation.Immutable;
import org.apache.http.auth.AuthProtocolState;
import org.apache.http.auth.AuthScheme;
import org.apache.http.auth.AuthScope;
import org.apache.http.auth.AuthStateHC4;
import org.apache.http.auth.Credentials;
import org.apache.http.client.AuthCache;
import org.apache.http.client.CredentialsProvider;
import org.apache.http.conn.routing.RouteInfo;
import org.apache.http.protocol.HttpContext;
import org.apache.http.util.Args;
/**
* Request interceptor that can preemptively authenticate against known hosts,
* if there is a cached {@link AuthScheme} instance in the local
* {@link AuthCache} associated with the given target or proxy host.
*
* @since 4.1
*/
@Immutable
public class RequestAuthCache implements HttpRequestInterceptor {
private final static String TAG = "HttpClient";
public RequestAuthCache() {
super();
}
public void process(final HttpRequest request, final HttpContext context)
throws HttpException, IOException {
Args.notNull(request, "HTTP request");
Args.notNull(context, "HTTP context");
final HttpClientContext clientContext = HttpClientContext.adapt(context);
final AuthCache authCache = clientContext.getAuthCache();
if (authCache == null) {
if (Log.isLoggable(TAG, Log.DEBUG)) {
Log.d(TAG, "Auth cache not set in the context");
}
return;
}
final CredentialsProvider credsProvider = clientContext.getCredentialsProvider();
if (credsProvider == null) {
if (Log.isLoggable(TAG, Log.DEBUG)) {
Log.d(TAG, "Credentials provider not set in the context");
}
return;
}
final RouteInfo route = clientContext.getHttpRoute();
if (route == null) {
if (Log.isLoggable(TAG, Log.DEBUG)) {
Log.d(TAG, "Route info not set in the context");
}
return;
}
HttpHost target = clientContext.getTargetHost();
if (target == null) {
if (Log.isLoggable(TAG, Log.DEBUG)) {
Log.d(TAG, "Target host not set in the context");
}
return;
}
if (target.getPort() < 0) {
target = new HttpHost(
target.getHostName(),
route.getTargetHost().getPort(),
target.getSchemeName());
}
final AuthStateHC4 targetState = clientContext.getTargetAuthState();
if (targetState != null && targetState.getState() == AuthProtocolState.UNCHALLENGED) {
final AuthScheme authScheme = authCache.get(target);
if (authScheme != null) {
doPreemptiveAuth(target, authScheme, targetState, credsProvider);
}
}
final HttpHost proxy = route.getProxyHost();
final AuthStateHC4 proxyState = clientContext.getProxyAuthState();
if (proxy != null && proxyState != null && proxyState.getState() == AuthProtocolState.UNCHALLENGED) {
final AuthScheme authScheme = authCache.get(proxy);
if (authScheme != null) {
doPreemptiveAuth(proxy, authScheme, proxyState, credsProvider);
}
}
}
private void doPreemptiveAuth(
final HttpHost host,
final AuthScheme authScheme,
final AuthStateHC4 authState,
final CredentialsProvider credsProvider) {
final String schemeName = authScheme.getSchemeName();
if (Log.isLoggable(TAG, Log.DEBUG)) {
Log.d(TAG, "Re-using cached '" + schemeName + "' auth scheme for " + host);
}
final AuthScope authScope = new AuthScope(host.getHostName(), host.getPort(), AuthScope.ANY_REALM, schemeName);
final Credentials creds = credsProvider.getCredentials(authScope);
if (creds != null) {
if ("BASIC".equalsIgnoreCase(authScheme.getSchemeName())) {
authState.setState(AuthProtocolState.CHALLENGED);
} else {
authState.setState(AuthProtocolState.SUCCESS);
}
authState.update(authScheme, creds);
} else {
if (Log.isLoggable(TAG, Log.DEBUG)) {
Log.d(TAG, "No credentials for preemptive authentication");
}
}
}
}

View File

@ -1,94 +0,0 @@
/*
* ====================================================================
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you under the Apache License, Version 2.0 (the
* "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
* KIND, either express or implied. See the License for the
* specific language governing permissions and limitations
* under the License.
* ====================================================================
*
* This software consists of voluntary contributions made by many
* individuals on behalf of the Apache Software Foundation. For more
* information on the Apache Software Foundation, please see
* <http://www.apache.org/>.
*
*/
package org.apache.http.client.protocol;
import java.io.IOException;
import android.util.Log;
import org.apache.http.HttpException;
import org.apache.http.HttpRequest;
import org.apache.http.HttpRequestInterceptor;
import org.apache.http.annotation.Immutable;
import org.apache.http.conn.routing.RouteInfo;
import org.apache.http.protocol.HTTP;
import org.apache.http.protocol.HttpContext;
import org.apache.http.util.Args;
/**
* This protocol interceptor is responsible for adding <code>Connection</code>
* or <code>Proxy-Connection</code> headers to the outgoing requests, which
* is essential for managing persistence of <code>HTTP/1.0</code> connections.
*
* @since 4.0
*/
@Immutable
public class RequestClientConnControl implements HttpRequestInterceptor {
private final static String TAG = "HttpClient";
private static final String PROXY_CONN_DIRECTIVE = "Proxy-Connection";
public RequestClientConnControl() {
super();
}
public void process(final HttpRequest request, final HttpContext context)
throws HttpException, IOException {
Args.notNull(request, "HTTP request");
final String method = request.getRequestLine().getMethod();
if (method.equalsIgnoreCase("CONNECT")) {
request.setHeader(PROXY_CONN_DIRECTIVE, HTTP.CONN_KEEP_ALIVE);
return;
}
final HttpClientContext clientContext = HttpClientContext.adapt(context);
// Obtain the client connection (required)
final RouteInfo route = clientContext.getHttpRoute();
if (route == null) {
if (Log.isLoggable(TAG, Log.DEBUG)) {
Log.d(TAG, "Connection route not set in the context");
}
return;
}
if (route.getHopCount() == 1 || route.isTunnelled()) {
if (!request.containsHeader(HTTP.CONN_DIRECTIVE)) {
request.addHeader(HTTP.CONN_DIRECTIVE, HTTP.CONN_KEEP_ALIVE);
}
}
if (route.getHopCount() == 2 && !route.isTunnelled()) {
if (!request.containsHeader(PROXY_CONN_DIRECTIVE)) {
request.addHeader(PROXY_CONN_DIRECTIVE, HTTP.CONN_KEEP_ALIVE);
}
}
}
}

View File

@ -1,89 +0,0 @@
/*
* ====================================================================
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you under the Apache License, Version 2.0 (the
* "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
* KIND, either express or implied. See the License for the
* specific language governing permissions and limitations
* under the License.
* ====================================================================
*
* This software consists of voluntary contributions made by many
* individuals on behalf of the Apache Software Foundation. For more
* information on the Apache Software Foundation, please see
* <http://www.apache.org/>.
*
*/
package org.apache.http.client.protocol;
import java.io.IOException;
import java.util.Collection;
import org.apache.http.Header;
import org.apache.http.HttpException;
import org.apache.http.HttpRequest;
import org.apache.http.HttpRequestInterceptor;
import org.apache.http.annotation.Immutable;
import org.apache.http.client.params.ClientPNames;
import org.apache.http.protocol.HttpContext;
import org.apache.http.util.Args;
/**
* Request interceptor that adds default request headers.
*
* @since 4.0
*/
@SuppressWarnings("deprecation")
@Immutable
public class RequestDefaultHeadersHC4 implements HttpRequestInterceptor {
private final Collection<? extends Header> defaultHeaders;
/**
* @since 4.3
*/
public RequestDefaultHeadersHC4(final Collection<? extends Header> defaultHeaders) {
super();
this.defaultHeaders = defaultHeaders;
}
public RequestDefaultHeadersHC4() {
this(null);
}
public void process(final HttpRequest request, final HttpContext context)
throws HttpException, IOException {
Args.notNull(request, "HTTP request");
final String method = request.getRequestLine().getMethod();
if (method.equalsIgnoreCase("CONNECT")) {
return;
}
// Add default headers
@SuppressWarnings("unchecked")
Collection<? extends Header> defHeaders = (Collection<? extends Header>)
request.getParams().getParameter(ClientPNames.DEFAULT_HEADERS);
if (defHeaders == null) {
defHeaders = this.defaultHeaders;
}
if (defHeaders != null) {
for (final Header defHeader : defHeaders) {
request.addHeader(defHeader);
}
}
}
}

View File

@ -1,82 +0,0 @@
/*
* ====================================================================
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you under the Apache License, Version 2.0 (the
* "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
* KIND, either express or implied. See the License for the
* specific language governing permissions and limitations
* under the License.
* ====================================================================
*
* This software consists of voluntary contributions made by many
* individuals on behalf of the Apache Software Foundation. For more
* information on the Apache Software Foundation, please see
* <http://www.apache.org/>.
*
*/
package org.apache.http.client.protocol;
import java.io.IOException;
import org.apache.http.HttpEntity;
import org.apache.http.HttpEntityEnclosingRequest;
import org.apache.http.HttpException;
import org.apache.http.HttpRequest;
import org.apache.http.HttpRequestInterceptor;
import org.apache.http.HttpVersion;
import org.apache.http.ProtocolVersion;
import org.apache.http.annotation.Immutable;
import org.apache.http.client.config.RequestConfig;
import org.apache.http.protocol.HTTP;
import org.apache.http.protocol.HttpContext;
import org.apache.http.util.Args;
/**
* RequestExpectContinue is responsible for enabling the 'expect-continue'
* handshake by adding <code>Expect</code> header.
* <p/>
* This interceptor takes into account {@link RequestConfig#isExpectContinueEnabled()}
* setting.
*
* @since 4.3
*/
@Immutable
public class RequestExpectContinue implements HttpRequestInterceptor {
public RequestExpectContinue() {
super();
}
public void process(final HttpRequest request, final HttpContext context)
throws HttpException, IOException {
Args.notNull(request, "HTTP request");
if (!request.containsHeader(HTTP.EXPECT_DIRECTIVE)) {
if (request instanceof HttpEntityEnclosingRequest) {
final ProtocolVersion ver = request.getRequestLine().getProtocolVersion();
final HttpEntity entity = ((HttpEntityEnclosingRequest)request).getEntity();
// Do not send the expect header if request body is known to be empty
if (entity != null
&& entity.getContentLength() != 0 && !ver.lessEquals(HttpVersion.HTTP_1_0)) {
final HttpClientContext clientContext = HttpClientContext.adapt(context);
final RequestConfig config = clientContext.getRequestConfig();
if (config.isExpectContinueEnabled()) {
request.addHeader(HTTP.EXPECT_DIRECTIVE, HTTP.EXPECT_CONTINUE);
}
}
}
}
}
}

View File

@ -1,110 +0,0 @@
/*
* ====================================================================
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you under the Apache License, Version 2.0 (the
* "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
* KIND, either express or implied. See the License for the
* specific language governing permissions and limitations
* under the License.
* ====================================================================
*
* This software consists of voluntary contributions made by many
* individuals on behalf of the Apache Software Foundation. For more
* information on the Apache Software Foundation, please see
* <http://www.apache.org/>.
*
*/
package org.apache.http.client.protocol;
import java.io.IOException;
import java.util.Locale;
import org.apache.http.Header;
import org.apache.http.HeaderElement;
import org.apache.http.HttpEntity;
import org.apache.http.HttpException;
import org.apache.http.HttpResponse;
import org.apache.http.HttpResponseInterceptor;
import org.apache.http.annotation.Immutable;
import org.apache.http.client.entity.DeflateDecompressingEntity;
import org.apache.http.client.entity.GzipDecompressingEntity;
import org.apache.http.protocol.HttpContext;
/**
* {@link HttpResponseInterceptor} responsible for processing Content-Encoding
* responses.
* <p>
* Instances of this class are stateless and immutable, therefore threadsafe.
*
* @since 4.1
*
*/
@Immutable
public class ResponseContentEncoding implements HttpResponseInterceptor {
public static final String UNCOMPRESSED = "http.client.response.uncompressed";
/**
* Handles the following {@code Content-Encoding}s by
* using the appropriate decompressor to wrap the response Entity:
* <ul>
* <li>gzip - see {@link GzipDecompressingEntity}</li>
* <li>deflate - see {@link DeflateDecompressingEntity}</li>
* <li>identity - no action needed</li>
* </ul>
*
* @param response the response which contains the entity
* @param context not currently used
*
* @throws HttpException if the {@code Content-Encoding} is none of the above
*/
public void process(
final HttpResponse response,
final HttpContext context) throws HttpException, IOException {
final HttpEntity entity = response.getEntity();
// entity can be null in case of 304 Not Modified, 204 No Content or similar
// check for zero length entity.
if (entity != null && entity.getContentLength() != 0) {
final Header ceheader = entity.getContentEncoding();
if (ceheader != null) {
final HeaderElement[] codecs = ceheader.getElements();
boolean uncompressed = false;
for (final HeaderElement codec : codecs) {
final String codecname = codec.getName().toLowerCase(Locale.ENGLISH);
if ("gzip".equals(codecname) || "x-gzip".equals(codecname)) {
response.setEntity(new GzipDecompressingEntity(response.getEntity()));
uncompressed = true;
break;
} else if ("deflate".equals(codecname)) {
response.setEntity(new DeflateDecompressingEntity(response.getEntity()));
uncompressed = true;
break;
} else if ("identity".equals(codecname)) {
/* Don't need to transform the content - no-op */
return;
} else {
throw new HttpException("Unsupported Content-Coding: " + codec.getName());
}
}
if (uncompressed) {
response.removeHeaders("Content-Length");
response.removeHeaders("Content-Encoding");
response.removeHeaders("Content-MD5");
}
}
}
}
}

View File

@ -1,162 +0,0 @@
/*
* ====================================================================
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you under the Apache License, Version 2.0 (the
* "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
* KIND, either express or implied. See the License for the
* specific language governing permissions and limitations
* under the License.
* ====================================================================
*
* This software consists of voluntary contributions made by many
* individuals on behalf of the Apache Software Foundation. For more
* information on the Apache Software Foundation, please see
* <http://www.apache.org/>.
*
*/
package org.apache.http.client.protocol;
import java.io.IOException;
import java.util.List;
import android.util.Log;
import org.apache.http.Header;
import org.apache.http.HeaderIterator;
import org.apache.http.HttpException;
import org.apache.http.HttpResponse;
import org.apache.http.HttpResponseInterceptor;
import org.apache.http.annotation.Immutable;
import org.apache.http.client.CookieStore;
import org.apache.http.cookie.Cookie;
import org.apache.http.cookie.CookieOrigin;
import org.apache.http.cookie.CookieSpec;
import org.apache.http.cookie.MalformedCookieException;
import org.apache.http.cookie.SM;
import org.apache.http.protocol.HttpContext;
import org.apache.http.util.Args;
/**
* Response interceptor that populates the current {@link CookieStore} with data
* contained in response cookies received in the given the HTTP response.
*
* @since 4.0
*/
@Immutable
public class ResponseProcessCookiesHC4 implements HttpResponseInterceptor {
private final static String TAG = "HttpClient";
public ResponseProcessCookiesHC4() {
super();
}
public void process(final HttpResponse response, final HttpContext context)
throws HttpException, IOException {
Args.notNull(response, "HTTP request");
Args.notNull(context, "HTTP context");
final HttpClientContext clientContext = HttpClientContext.adapt(context);
// Obtain actual CookieSpec instance
final CookieSpec cookieSpec = clientContext.getCookieSpec();
if (cookieSpec == null) {
if (Log.isLoggable(TAG, Log.DEBUG)) {
Log.d(TAG, "Cookie spec not specified in HTTP context");
}
return;
}
// Obtain cookie store
final CookieStore cookieStore = clientContext.getCookieStore();
if (cookieStore == null) {
if (Log.isLoggable(TAG, Log.DEBUG)) {
Log.d(TAG, "Cookie store not specified in HTTP context");
}
return;
}
// Obtain actual CookieOrigin instance
final CookieOrigin cookieOrigin = clientContext.getCookieOrigin();
if (cookieOrigin == null) {
if (Log.isLoggable(TAG, Log.DEBUG)) {
Log.d(TAG, "Cookie origin not specified in HTTP context");
}
return;
}
HeaderIterator it = response.headerIterator(SM.SET_COOKIE);
processCookies(it, cookieSpec, cookieOrigin, cookieStore);
// see if the cookie spec supports cookie versioning.
if (cookieSpec.getVersion() > 0) {
// process set-cookie2 headers.
// Cookie2 will replace equivalent Cookie instances
it = response.headerIterator(SM.SET_COOKIE2);
processCookies(it, cookieSpec, cookieOrigin, cookieStore);
}
}
private void processCookies(
final HeaderIterator iterator,
final CookieSpec cookieSpec,
final CookieOrigin cookieOrigin,
final CookieStore cookieStore) {
while (iterator.hasNext()) {
final Header header = iterator.nextHeader();
try {
final List<Cookie> cookies = cookieSpec.parse(header, cookieOrigin);
for (final Cookie cookie : cookies) {
try {
cookieSpec.validate(cookie, cookieOrigin);
cookieStore.addCookie(cookie);
if (Log.isLoggable(TAG, Log.DEBUG)) {
Log.d(TAG, "Cookie accepted [" + formatCooke(cookie) + "]");
}
} catch (final MalformedCookieException ex) {
if (Log.isLoggable(TAG, Log.WARN)) {
Log.w(TAG, "Cookie rejected [" + formatCooke(cookie) + "] "
+ ex.getMessage());
}
}
}
} catch (final MalformedCookieException ex) {
if (Log.isLoggable(TAG, Log.WARN)) {
Log.w(TAG, "Invalid cookie header: \""
+ header + "\". " + ex.getMessage());
}
}
}
}
private static String formatCooke(final Cookie cookie) {
final StringBuilder buf = new StringBuilder();
buf.append(cookie.getName());
buf.append("=\"");
String v = cookie.getValue();
if (v.length() > 100) {
v = v.substring(0, 100) + "...";
}
buf.append(v);
buf.append("\"");
buf.append(", version:");
buf.append(Integer.toString(cookie.getVersion()));
buf.append(", domain:");
buf.append(cookie.getDomain());
buf.append(", path:");
buf.append(cookie.getPath());
buf.append(", expiry:");
buf.append(cookie.getExpiryDate());
return buf.toString();
}
}

View File

@ -1,31 +0,0 @@
/*
* ====================================================================
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you under the Apache License, Version 2.0 (the
* "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
* KIND, either express or implied. See the License for the
* specific language governing permissions and limitations
* under the License.
* ====================================================================
*
* This software consists of voluntary contributions made by many
* individuals on behalf of the Apache Software Foundation. For more
* information on the Apache Software Foundation, please see
* <http://www.apache.org/>.
*
*/
/**
* Client specific HTTP protocol handlers.
*/
package org.apache.http.client.protocol;

View File

@ -1,86 +0,0 @@
/*
* ====================================================================
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you under the Apache License, Version 2.0 (the
* "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
* KIND, either express or implied. See the License for the
* specific language governing permissions and limitations
* under the License.
* ====================================================================
*
* This software consists of voluntary contributions made by many
* individuals on behalf of the Apache Software Foundation. For more
* information on the Apache Software Foundation, please see
* <http://www.apache.org/>.
*
*/
package org.apache.http.client.utils;
import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;
import org.apache.http.annotation.Immutable;
/**
* A collection of utilities to workaround limitations of Java clone framework.
*
* @since 4.0
*/
@Immutable
public class CloneUtilsHC4 {
/**
* @since 4.3
*/
public static <T> T cloneObject(final T obj) throws CloneNotSupportedException {
if (obj == null) {
return null;
}
if (obj instanceof Cloneable) {
final Class<?> clazz = obj.getClass ();
final Method m;
try {
m = clazz.getMethod("clone", (Class[]) null);
} catch (final NoSuchMethodException ex) {
throw new NoSuchMethodError(ex.getMessage());
}
try {
@SuppressWarnings("unchecked") // OK because clone() preserves the class
final T result = (T) m.invoke(obj, (Object []) null);
return result;
} catch (final InvocationTargetException ex) {
final Throwable cause = ex.getCause();
if (cause instanceof CloneNotSupportedException) {
throw ((CloneNotSupportedException) cause);
} else {
throw new Error("Unexpected exception", cause);
}
} catch (final IllegalAccessException ex) {
throw new IllegalAccessError(ex.getMessage());
}
} else {
throw new CloneNotSupportedException();
}
}
public static Object clone(final Object obj) throws CloneNotSupportedException {
return cloneObject(obj);
}
/**
* This class should not be instantiated.
*/
private CloneUtilsHC4() {
}
}

View File

@ -1,250 +0,0 @@
/*
* ====================================================================
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you under the Apache License, Version 2.0 (the
* "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
* KIND, either express or implied. See the License for the
* specific language governing permissions and limitations
* under the License.
* ====================================================================
*
* This software consists of voluntary contributions made by many
* individuals on behalf of the Apache Software Foundation. For more
* information on the Apache Software Foundation, please see
* <http://www.apache.org/>.
*
*/
package org.apache.http.client.utils;
import java.lang.ref.SoftReference;
import java.text.ParsePosition;
import java.text.SimpleDateFormat;
import java.util.Calendar;
import java.util.Date;
import java.util.HashMap;
import java.util.Locale;
import java.util.Map;
import java.util.TimeZone;
import org.apache.http.annotation.Immutable;
import org.apache.http.util.Args;
/**
* A utility class for parsing and formatting HTTP dates as used in cookies and
* other headers. This class handles dates as defined by RFC 2616 section
* 3.3.1 as well as some other common non-standard formats.
*
* @since 4.3
*/
@Immutable
public final class DateUtils {
/**
* Date format pattern used to parse HTTP date headers in RFC 1123 format.
*/
public static final String PATTERN_RFC1123 = "EEE, dd MMM yyyy HH:mm:ss zzz";
/**
* Date format pattern used to parse HTTP date headers in RFC 1036 format.
*/
public static final String PATTERN_RFC1036 = "EEE, dd-MMM-yy HH:mm:ss zzz";
/**
* Date format pattern used to parse HTTP date headers in ANSI C
* <code>asctime()</code> format.
*/
public static final String PATTERN_ASCTIME = "EEE MMM d HH:mm:ss yyyy";
private static final String[] DEFAULT_PATTERNS = new String[] {
PATTERN_RFC1123,
PATTERN_RFC1036,
PATTERN_ASCTIME
};
private static final Date DEFAULT_TWO_DIGIT_YEAR_START;
public static final TimeZone GMT = TimeZone.getTimeZone("GMT");
static {
final Calendar calendar = Calendar.getInstance();
calendar.setTimeZone(GMT);
calendar.set(2000, Calendar.JANUARY, 1, 0, 0, 0);
calendar.set(Calendar.MILLISECOND, 0);
DEFAULT_TWO_DIGIT_YEAR_START = calendar.getTime();
}
/**
* Parses a date value. The formats used for parsing the date value are retrieved from
* the default http params.
*
* @param dateValue the date value to parse
*
* @return the parsed date or null if input could not be parsed
*/
public static Date parseDate(final String dateValue) {
return parseDate(dateValue, null, null);
}
/**
* Parses the date value using the given date formats.
*
* @param dateValue the date value to parse
* @param dateFormats the date formats to use
*
* @return the parsed date or null if input could not be parsed
*/
public static Date parseDate(final String dateValue, final String[] dateFormats) {
return parseDate(dateValue, dateFormats, null);
}
/**
* Parses the date value using the given date formats.
*
* @param dateValue the date value to parse
* @param dateFormats the date formats to use
* @param startDate During parsing, two digit years will be placed in the range
* <code>startDate</code> to <code>startDate + 100 years</code>. This value may
* be <code>null</code>. When <code>null</code> is given as a parameter, year
* <code>2000</code> will be used.
*
* @return the parsed date or null if input could not be parsed
*/
public static Date parseDate(
final String dateValue,
final String[] dateFormats,
final Date startDate) {
Args.notNull(dateValue, "Date value");
final String[] localDateFormats = dateFormats != null ? dateFormats : DEFAULT_PATTERNS;
final Date localStartDate = startDate != null ? startDate : DEFAULT_TWO_DIGIT_YEAR_START;
String v = dateValue;
// trim single quotes around date if present
// see issue #5279
if (v.length() > 1 && v.startsWith("'") && v.endsWith("'")) {
v = v.substring (1, v.length() - 1);
}
for (final String dateFormat : localDateFormats) {
final SimpleDateFormat dateParser = DateFormatHolder.formatFor(dateFormat);
dateParser.set2DigitYearStart(localStartDate);
final ParsePosition pos = new ParsePosition(0);
final Date result = dateParser.parse(v, pos);
if (pos.getIndex() != 0) {
return result;
}
}
return null;
}
/**
* Formats the given date according to the RFC 1123 pattern.
*
* @param date The date to format.
* @return An RFC 1123 formatted date string.
*
* @see #PATTERN_RFC1123
*/
public static String formatDate(final Date date) {
return formatDate(date, PATTERN_RFC1123);
}
/**
* Formats the given date according to the specified pattern. The pattern
* must conform to that used by the {@link SimpleDateFormat simple date
* format} class.
*
* @param date The date to format.
* @param pattern The pattern to use for formatting the date.
* @return A formatted date string.
*
* @throws IllegalArgumentException If the given date pattern is invalid.
*
* @see SimpleDateFormat
*/
public static String formatDate(final Date date, final String pattern) {
Args.notNull(date, "Date");
Args.notNull(pattern, "Pattern");
final SimpleDateFormat formatter = DateFormatHolder.formatFor(pattern);
return formatter.format(date);
}
/**
* Clears thread-local variable containing {@link java.text.DateFormat} cache.
*
* @since 4.3
*/
public static void clearThreadLocal() {
DateFormatHolder.clearThreadLocal();
}
/** This class should not be instantiated. */
private DateUtils() {
}
/**
* A factory for {@link SimpleDateFormat}s. The instances are stored in a
* threadlocal way because SimpleDateFormat is not threadsafe as noted in
* {@link SimpleDateFormat its javadoc}.
*
*/
final static class DateFormatHolder {
private static final ThreadLocal<SoftReference<Map<String, SimpleDateFormat>>>
THREADLOCAL_FORMATS = new ThreadLocal<SoftReference<Map<String, SimpleDateFormat>>>() {
@Override
protected SoftReference<Map<String, SimpleDateFormat>> initialValue() {
return new SoftReference<Map<String, SimpleDateFormat>>(
new HashMap<String, SimpleDateFormat>());
}
};
/**
* creates a {@link SimpleDateFormat} for the requested format string.
*
* @param pattern
* a non-<code>null</code> format String according to
* {@link SimpleDateFormat}. The format is not checked against
* <code>null</code> since all paths go through
* {@link DateUtils}.
* @return the requested format. This simple dateformat should not be used
* to {@link SimpleDateFormat#applyPattern(String) apply} to a
* different pattern.
*/
public static SimpleDateFormat formatFor(final String pattern) {
final SoftReference<Map<String, SimpleDateFormat>> ref = THREADLOCAL_FORMATS.get();
Map<String, SimpleDateFormat> formats = ref.get();
if (formats == null) {
formats = new HashMap<String, SimpleDateFormat>();
THREADLOCAL_FORMATS.set(
new SoftReference<Map<String, SimpleDateFormat>>(formats));
}
SimpleDateFormat format = formats.get(pattern);
if (format == null) {
format = new SimpleDateFormat(pattern, Locale.US);
format.setTimeZone(TimeZone.getTimeZone("GMT"));
formats.put(pattern, format);
}
return format;
}
public static void clearThreadLocal() {
THREADLOCAL_FORMATS.remove();
}
}
}

View File

@ -1,149 +0,0 @@
/*
* ====================================================================
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you under the Apache License, Version 2.0 (the
* "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
* KIND, either express or implied. See the License for the
* specific language governing permissions and limitations
* under the License.
* ====================================================================
*
* This software consists of voluntary contributions made by many
* individuals on behalf of the Apache Software Foundation. For more
* information on the Apache Software Foundation, please see
* <http://www.apache.org/>.
*
*/
package org.apache.http.client.utils;
import java.io.Closeable;
import java.io.IOException;
import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.client.HttpClient;
import org.apache.http.client.methods.CloseableHttpResponse;
import org.apache.http.util.EntityUtilsHC4;
/**
* Convenience methods for closing response and client objects.
*
* @since 4.2
*/
public class HttpClientUtils {
private HttpClientUtils() {
}
/**
* Unconditionally close a response.
* <p>
* Example Code:
*
* <pre>
* HttpResponse httpResponse = null;
* try {
* httpResponse = httpClient.execute(httpGet);
* } catch (Exception e) {
* // error handling
* } finally {
* HttpClientUtils.closeQuietly(httpResponse);
* }
* </pre>
*
* @param response
* the HttpResponse to release resources, may be null or already
* closed.
*
* @since 4.2
*/
public static void closeQuietly(final HttpResponse response) {
if (response != null) {
final HttpEntity entity = response.getEntity();
if (entity != null) {
try {
EntityUtilsHC4.consume(entity);
} catch (final IOException ex) {
}
}
}
}
/**
* Unconditionally close a response.
* <p>
* Example Code:
*
* <pre>
* HttpResponse httpResponse = null;
* try {
* httpResponse = httpClient.execute(httpGet);
* } catch (Exception e) {
* // error handling
* } finally {
* HttpClientUtils.closeQuietly(httpResponse);
* }
* </pre>
*
* @param response
* the HttpResponse to release resources, may be null or already
* closed.
*
* @since 4.3
*/
public static void closeQuietly(final CloseableHttpResponse response) {
if (response != null) {
try {
try {
EntityUtilsHC4.consume(response.getEntity());
} finally {
response.close();
}
} catch (final IOException ignore) {
}
}
}
/**
* Unconditionally close a httpClient. Shuts down the underlying connection
* manager and releases the resources.
* <p>
* Example Code:
*
* <pre>
* HttpClient httpClient = HttpClients.createDefault();
* try {
* httpClient.execute(request);
* } catch (Exception e) {
* // error handling
* } finally {
* HttpClientUtils.closeQuietly(httpClient);
* }
* </pre>
*
* @param httpClient
* the HttpClient to close, may be null or already closed.
* @since 4.2
*/
public static void closeQuietly(final HttpClient httpClient) {
if (httpClient != null) {
if (httpClient instanceof Closeable) {
try {
((Closeable) httpClient).close();
} catch (final IOException ignore) {
}
}
}
}
}

View File

@ -1,42 +0,0 @@
/*
* ====================================================================
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you under the Apache License, Version 2.0 (the
* "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
* KIND, either express or implied. See the License for the
* specific language governing permissions and limitations
* under the License.
* ====================================================================
*
* This software consists of voluntary contributions made by many
* individuals on behalf of the Apache Software Foundation. For more
* information on the Apache Software Foundation, please see
* <http://www.apache.org/>.
*
*/
package org.apache.http.client.utils;
/**
* Abstraction of international domain name (IDN) conversion.
*
* @since 4.0
*/
public interface Idn {
/**
* Converts a name from its punycode representation to Unicode.
* The name may be a single hostname or a dot-separated qualified domain name.
* @param punycode the Punycode representation
* @return the Unicode domain name
*/
String toUnicode(String punycode);
}

View File

@ -1,71 +0,0 @@
/*
* ====================================================================
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you under the Apache License, Version 2.0 (the
* "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
* KIND, either express or implied. See the License for the
* specific language governing permissions and limitations
* under the License.
* ====================================================================
*
* This software consists of voluntary contributions made by many
* individuals on behalf of the Apache Software Foundation. For more
* information on the Apache Software Foundation, please see
* <http://www.apache.org/>.
*
*/
package org.apache.http.client.utils;
import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;
import org.apache.http.annotation.Immutable;
/**
* Uses the java.net.IDN class through reflection.
*
* @since 4.0
*/
@Immutable
public class JdkIdn implements Idn {
private final Method toUnicode;
/**
*
* @throws ClassNotFoundException if java.net.IDN is not available
*/
public JdkIdn() throws ClassNotFoundException {
final Class<?> clazz = Class.forName("java.net.IDN");
try {
toUnicode = clazz.getMethod("toUnicode", String.class);
} catch (final SecurityException e) {
// doesn't happen
throw new IllegalStateException(e.getMessage(), e);
} catch (final NoSuchMethodException e) {
// doesn't happen
throw new IllegalStateException(e.getMessage(), e);
}
}
public String toUnicode(final String punycode) {
try {
return (String) toUnicode.invoke(null, punycode);
} catch (final IllegalAccessException e) {
throw new IllegalStateException(e.getMessage(), e);
} catch (final InvocationTargetException e) {
final Throwable t = e.getCause();
throw new RuntimeException(t.getMessage(), t);
}
}
}

View File

@ -1,54 +0,0 @@
/*
* ====================================================================
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you under the Apache License, Version 2.0 (the
* "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
* KIND, either express or implied. See the License for the
* specific language governing permissions and limitations
* under the License.
* ====================================================================
*
* This software consists of voluntary contributions made by many
* individuals on behalf of the Apache Software Foundation. For more
* information on the Apache Software Foundation, please see
* <http://www.apache.org/>.
*
*/
package org.apache.http.client.utils;
import org.apache.http.annotation.Immutable;
/**
* Facade that provides conversion between Unicode and Punycode domain names.
* It will use an appropriate implementation.
*
* @since 4.0
*/
@Immutable
public class Punycode {
private static final Idn impl;
static {
Idn _impl;
try {
_impl = new JdkIdn();
} catch (final Exception e) {
_impl = new Rfc3492Idn();
}
impl = _impl;
}
public static String toUnicode(final String punycode) {
return impl.toUnicode(punycode);
}
}

View File

@ -1,141 +0,0 @@
/*
* ====================================================================
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you under the Apache License, Version 2.0 (the
* "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
* KIND, either express or implied. See the License for the
* specific language governing permissions and limitations
* under the License.
* ====================================================================
*
* This software consists of voluntary contributions made by many
* individuals on behalf of the Apache Software Foundation. For more
* information on the Apache Software Foundation, please see
* <http://www.apache.org/>.
*
*/
package org.apache.http.client.utils;
import java.util.StringTokenizer;
import org.apache.http.annotation.Immutable;
/**
* Implementation from pseudo code in RFC 3492.
*
* @since 4.0
*/
@Immutable
public class Rfc3492Idn implements Idn {
private static final int base = 36;
private static final int tmin = 1;
private static final int tmax = 26;
private static final int skew = 38;
private static final int damp = 700;
private static final int initial_bias = 72;
private static final int initial_n = 128;
private static final char delimiter = '-';
private static final String ACE_PREFIX = "xn--";
private int adapt(final int delta, final int numpoints, final boolean firsttime) {
int d = delta;
if (firsttime) {
d = d / damp;
} else {
d = d / 2;
}
d = d + (d / numpoints);
int k = 0;
while (d > ((base - tmin) * tmax) / 2) {
d = d / (base - tmin);
k = k + base;
}
return k + (((base - tmin + 1) * d) / (d + skew));
}
private int digit(final char c) {
if ((c >= 'A') && (c <= 'Z')) {
return (c - 'A');
}
if ((c >= 'a') && (c <= 'z')) {
return (c - 'a');
}
if ((c >= '0') && (c <= '9')) {
return (c - '0') + 26;
}
throw new IllegalArgumentException("illegal digit: "+ c);
}
public String toUnicode(final String punycode) {
final StringBuilder unicode = new StringBuilder(punycode.length());
final StringTokenizer tok = new StringTokenizer(punycode, ".");
while (tok.hasMoreTokens()) {
String t = tok.nextToken();
if (unicode.length() > 0) {
unicode.append('.');
}
if (t.startsWith(ACE_PREFIX)) {
t = decode(t.substring(4));
}
unicode.append(t);
}
return unicode.toString();
}
protected String decode(final String s) {
String input = s;
int n = initial_n;
int i = 0;
int bias = initial_bias;
final StringBuilder output = new StringBuilder(input.length());
final int lastdelim = input.lastIndexOf(delimiter);
if (lastdelim != -1) {
output.append(input.subSequence(0, lastdelim));
input = input.substring(lastdelim + 1);
}
while (input.length() > 0) {
final int oldi = i;
int w = 1;
for (int k = base;; k += base) {
if (input.length() == 0) {
break;
}
final char c = input.charAt(0);
input = input.substring(1);
final int digit = digit(c);
i = i + digit * w; // FIXME fail on overflow
final int t;
if (k <= bias + tmin) {
t = tmin;
} else if (k >= bias + tmax) {
t = tmax;
} else {
t = k - bias;
}
if (digit < t) {
break;
}
w = w * (base - t); // FIXME fail on overflow
}
bias = adapt(i - oldi, output.length() + 1, (oldi == 0));
n = n + i / (output.length() + 1); // FIXME fail on overflow
i = i % (output.length() + 1);
// {if n is a basic code point then fail}
output.insert(i, (char) n);
i++;
}
return output.toString();
}
}

View File

@ -1,490 +0,0 @@
/*
* ====================================================================
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you under the Apache License, Version 2.0 (the
* "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
* KIND, either express or implied. See the License for the
* specific language governing permissions and limitations
* under the License.
* ====================================================================
*
* This software consists of voluntary contributions made by many
* individuals on behalf of the Apache Software Foundation. For more
* information on the Apache Software Foundation, please see
* <http://www.apache.org/>.
*
*/
package org.apache.http.client.utils;
import java.net.URI;
import java.net.URISyntaxException;
import java.nio.charset.Charset;
import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;
import org.apache.http.Consts;
import org.apache.http.NameValuePair;
import org.apache.http.annotation.NotThreadSafe;
import org.apache.http.conn.util.InetAddressUtilsHC4;
import org.apache.http.message.BasicNameValuePair;
/**
* Builder for {@link URI} instances.
*
* @since 4.2
*/
@NotThreadSafe
public class URIBuilder {
private String scheme;
private String encodedSchemeSpecificPart;
private String encodedAuthority;
private String userInfo;
private String encodedUserInfo;
private String host;
private int port;
private String path;
private String encodedPath;
private String encodedQuery;
private List<NameValuePair> queryParams;
private String query;
private String fragment;
private String encodedFragment;
/**
* Constructs an empty instance.
*/
public URIBuilder() {
super();
this.port = -1;
}
/**
* Construct an instance from the string which must be a valid URI.
*
* @param string a valid URI in string form
* @throws URISyntaxException if the input is not a valid URI
*/
public URIBuilder(final String string) throws URISyntaxException {
super();
digestURI(new URI(string));
}
/**
* Construct an instance from the provided URI.
* @param uri
*/
public URIBuilder(final URI uri) {
super();
digestURI(uri);
}
private List <NameValuePair> parseQuery(final String query, final Charset charset) {
if (query != null && query.length() > 0) {
return URLEncodedUtilsHC4.parse(query, charset);
}
return null;
}
/**
* Builds a {@link URI} instance.
*/
public URI build() throws URISyntaxException {
return new URI(buildString());
}
private String buildString() {
final StringBuilder sb = new StringBuilder();
if (this.scheme != null) {
sb.append(this.scheme).append(':');
}
if (this.encodedSchemeSpecificPart != null) {
sb.append(this.encodedSchemeSpecificPart);
} else {
if (this.encodedAuthority != null) {
sb.append("//").append(this.encodedAuthority);
} else if (this.host != null) {
sb.append("//");
if (this.encodedUserInfo != null) {
sb.append(this.encodedUserInfo).append("@");
} else if (this.userInfo != null) {
sb.append(encodeUserInfo(this.userInfo)).append("@");
}
if (InetAddressUtilsHC4.isIPv6Address(this.host)) {
sb.append("[").append(this.host).append("]");
} else {
sb.append(this.host);
}
if (this.port >= 0) {
sb.append(":").append(this.port);
}
}
if (this.encodedPath != null) {
sb.append(normalizePath(this.encodedPath));
} else if (this.path != null) {
sb.append(encodePath(normalizePath(this.path)));
}
if (this.encodedQuery != null) {
sb.append("?").append(this.encodedQuery);
} else if (this.queryParams != null) {
sb.append("?").append(encodeUrlForm(this.queryParams));
} else if (this.query != null) {
sb.append("?").append(encodeUric(this.query));
}
}
if (this.encodedFragment != null) {
sb.append("#").append(this.encodedFragment);
} else if (this.fragment != null) {
sb.append("#").append(encodeUric(this.fragment));
}
return sb.toString();
}
private void digestURI(final URI uri) {
this.scheme = uri.getScheme();
this.encodedSchemeSpecificPart = uri.getRawSchemeSpecificPart();
this.encodedAuthority = uri.getRawAuthority();
this.host = uri.getHost();
this.port = uri.getPort();
this.encodedUserInfo = uri.getRawUserInfo();
this.userInfo = uri.getUserInfo();
this.encodedPath = uri.getRawPath();
this.path = uri.getPath();
this.encodedQuery = uri.getRawQuery();
this.queryParams = parseQuery(uri.getRawQuery(), Consts.UTF_8);
this.encodedFragment = uri.getRawFragment();
this.fragment = uri.getFragment();
}
private String encodeUserInfo(final String userInfo) {
return URLEncodedUtilsHC4.encUserInfo(userInfo, Consts.UTF_8);
}
private String encodePath(final String path) {
return URLEncodedUtilsHC4.encPath(path, Consts.UTF_8);
}
private String encodeUrlForm(final List<NameValuePair> params) {
return URLEncodedUtilsHC4.format(params, Consts.UTF_8);
}
private String encodeUric(final String fragment) {
return URLEncodedUtilsHC4.encUric(fragment, Consts.UTF_8);
}
/**
* Sets URI scheme.
*/
public URIBuilder setScheme(final String scheme) {
this.scheme = scheme;
return this;
}
/**
* Sets URI user info. The value is expected to be unescaped and may contain non ASCII
* characters.
*/
public URIBuilder setUserInfo(final String userInfo) {
this.userInfo = userInfo;
this.encodedSchemeSpecificPart = null;
this.encodedAuthority = null;
this.encodedUserInfo = null;
return this;
}
/**
* Sets URI user info as a combination of username and password. These values are expected to
* be unescaped and may contain non ASCII characters.
*/
public URIBuilder setUserInfo(final String username, final String password) {
return setUserInfo(username + ':' + password);
}
/**
* Sets URI host.
*/
public URIBuilder setHost(final String host) {
this.host = host;
this.encodedSchemeSpecificPart = null;
this.encodedAuthority = null;
return this;
}
/**
* Sets URI port.
*/
public URIBuilder setPort(final int port) {
this.port = port < 0 ? -1 : port;
this.encodedSchemeSpecificPart = null;
this.encodedAuthority = null;
return this;
}
/**
* Sets URI path. The value is expected to be unescaped and may contain non ASCII characters.
*/
public URIBuilder setPath(final String path) {
this.path = path;
this.encodedSchemeSpecificPart = null;
this.encodedPath = null;
return this;
}
/**
* Removes URI query.
*/
public URIBuilder removeQuery() {
this.queryParams = null;
this.query = null;
this.encodedQuery = null;
this.encodedSchemeSpecificPart = null;
return this;
}
/**
* Sets URI query.
* <p>
* The value is expected to be encoded form data.
*
* @deprecated (4.3) use {@link #setParameters(List)} or {@link #setParameters(NameValuePair...)}
*
* @see URLEncodedUtilsHC4#parse
*/
@Deprecated
public URIBuilder setQuery(final String query) {
this.queryParams = parseQuery(query, Consts.UTF_8);
this.query = null;
this.encodedQuery = null;
this.encodedSchemeSpecificPart = null;
return this;
}
/**
* Sets URI query parameters. The parameter name / values are expected to be unescaped
* and may contain non ASCII characters.
* <p/>
* Please note query parameters and custom query component are mutually exclusive. This method
* will remove custom query if present.
*
* @since 4.3
*/
public URIBuilder setParameters(final List <NameValuePair> nvps) {
if (this.queryParams == null) {
this.queryParams = new ArrayList<NameValuePair>();
} else {
this.queryParams.clear();
}
this.queryParams.addAll(nvps);
this.encodedQuery = null;
this.encodedSchemeSpecificPart = null;
this.query = null;
return this;
}
/**
* Adds URI query parameters. The parameter name / values are expected to be unescaped
* and may contain non ASCII characters.
* <p/>
* Please note query parameters and custom query component are mutually exclusive. This method
* will remove custom query if present.
*
* @since 4.3
*/
public URIBuilder addParameters(final List <NameValuePair> nvps) {
if (this.queryParams == null) {
this.queryParams = new ArrayList<NameValuePair>();
}
this.queryParams.addAll(nvps);
this.encodedQuery = null;
this.encodedSchemeSpecificPart = null;
this.query = null;
return this;
}
/**
* Sets URI query parameters. The parameter name / values are expected to be unescaped
* and may contain non ASCII characters.
* <p/>
* Please note query parameters and custom query component are mutually exclusive. This method
* will remove custom query if present.
*
* @since 4.3
*/
public URIBuilder setParameters(final NameValuePair... nvps) {
if (this.queryParams == null) {
this.queryParams = new ArrayList<NameValuePair>();
} else {
this.queryParams.clear();
}
for (final NameValuePair nvp: nvps) {
this.queryParams.add(nvp);
}
this.encodedQuery = null;
this.encodedSchemeSpecificPart = null;
this.query = null;
return this;
}
/**
* Adds parameter to URI query. The parameter name and value are expected to be unescaped
* and may contain non ASCII characters.
* <p/>
* Please note query parameters and custom query component are mutually exclusive. This method
* will remove custom query if present.
*/
public URIBuilder addParameter(final String param, final String value) {
if (this.queryParams == null) {
this.queryParams = new ArrayList<NameValuePair>();
}
this.queryParams.add(new BasicNameValuePair(param, value));
this.encodedQuery = null;
this.encodedSchemeSpecificPart = null;
this.query = null;
return this;
}
/**
* Sets parameter of URI query overriding existing value if set. The parameter name and value
* are expected to be unescaped and may contain non ASCII characters.
* <p/>
* Please note query parameters and custom query component are mutually exclusive. This method
* will remove custom query if present.
*/
public URIBuilder setParameter(final String param, final String value) {
if (this.queryParams == null) {
this.queryParams = new ArrayList<NameValuePair>();
}
if (!this.queryParams.isEmpty()) {
for (final Iterator<NameValuePair> it = this.queryParams.iterator(); it.hasNext(); ) {
final NameValuePair nvp = it.next();
if (nvp.getName().equals(param)) {
it.remove();
}
}
}
this.queryParams.add(new BasicNameValuePair(param, value));
this.encodedQuery = null;
this.encodedSchemeSpecificPart = null;
this.query = null;
return this;
}
/**
* Clears URI query parameters.
*
* @since 4.3
*/
public URIBuilder clearParameters() {
this.queryParams = null;
this.encodedQuery = null;
this.encodedSchemeSpecificPart = null;
return this;
}
/**
* Sets custom URI query. The value is expected to be unescaped and may contain non ASCII
* characters.
* <p/>
* Please note query parameters and custom query component are mutually exclusive. This method
* will remove query parameters if present.
*
* @since 4.3
*/
public URIBuilder setCustomQuery(final String query) {
this.query = query;
this.encodedQuery = null;
this.encodedSchemeSpecificPart = null;
this.queryParams = null;
return this;
}
/**
* Sets URI fragment. The value is expected to be unescaped and may contain non ASCII
* characters.
*/
public URIBuilder setFragment(final String fragment) {
this.fragment = fragment;
this.encodedFragment = null;
return this;
}
/**
* @since 4.3
*/
public boolean isAbsolute() {
return this.scheme != null;
}
/**
* @since 4.3
*/
public boolean isOpaque() {
return this.path == null;
}
public String getScheme() {
return this.scheme;
}
public String getUserInfo() {
return this.userInfo;
}
public String getHost() {
return this.host;
}
public int getPort() {
return this.port;
}
public String getPath() {
return this.path;
}
public List<NameValuePair> getQueryParams() {
if (this.queryParams != null) {
return new ArrayList<NameValuePair>(this.queryParams);
} else {
return new ArrayList<NameValuePair>();
}
}
public String getFragment() {
return this.fragment;
}
@Override
public String toString() {
return buildString();
}
private static String normalizePath(final String path) {
String s = path;
if (s == null) {
return null;
}
int n = 0;
for (; n < s.length(); n++) {
if (s.charAt(n) != '/') {
break;
}
}
if (n > 1) {
s = s.substring(n - 1);
}
return s;
}
}

View File

@ -1,428 +0,0 @@
/*
* ====================================================================
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you under the Apache License, Version 2.0 (the
* "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
* KIND, either express or implied. See the License for the
* specific language governing permissions and limitations
* under the License.
* ====================================================================
*
* This software consists of voluntary contributions made by many
* individuals on behalf of the Apache Software Foundation. For more
* information on the Apache Software Foundation, please see
* <http://www.apache.org/>.
*
*/
package org.apache.http.client.utils;
import java.net.URI;
import java.net.URISyntaxException;
import java.util.List;
import java.util.Locale;
import java.util.Stack;
import org.apache.http.HttpHost;
import org.apache.http.annotation.Immutable;
import org.apache.http.util.Args;
import org.apache.http.util.TextUtils;
/**
* A collection of utilities for {@link URI URIs}, to workaround
* bugs within the class or for ease-of-use features.
*
* @since 4.0
*/
@Immutable
public class URIUtilsHC4 {
/**
* Constructs a {@link URI} using all the parameters. This should be
* used instead of
* {@link URI#URI(String, String, String, int, String, String, String)}
* or any of the other URI multi-argument URI constructors.
*
* @param scheme
* Scheme name
* @param host
* Host name
* @param port
* Port number
* @param path
* Path
* @param query
* Query
* @param fragment
* Fragment
*
* @throws URISyntaxException
* If both a scheme and a path are given but the path is
* relative, if the URI string constructed from the given
* components violates RFC&nbsp;2396, or if the authority
* component of the string is present but cannot be parsed
* as a server-based authority
*
* @deprecated (4.2) use {@link URIBuilder}.
*/
@Deprecated
public static URI createURI(
final String scheme,
final String host,
final int port,
final String path,
final String query,
final String fragment) throws URISyntaxException {
final StringBuilder buffer = new StringBuilder();
if (host != null) {
if (scheme != null) {
buffer.append(scheme);
buffer.append("://");
}
buffer.append(host);
if (port > 0) {
buffer.append(':');
buffer.append(port);
}
}
if (path == null || !path.startsWith("/")) {
buffer.append('/');
}
if (path != null) {
buffer.append(path);
}
if (query != null) {
buffer.append('?');
buffer.append(query);
}
if (fragment != null) {
buffer.append('#');
buffer.append(fragment);
}
return new URI(buffer.toString());
}
/**
* A convenience method for creating a new {@link URI} whose scheme, host
* and port are taken from the target host, but whose path, query and
* fragment are taken from the existing URI. The fragment is only used if
* dropFragment is false. The path is set to "/" if not explicitly specified.
*
* @param uri
* Contains the path, query and fragment to use.
* @param target
* Contains the scheme, host and port to use.
* @param dropFragment
* True if the fragment should not be copied.
*
* @throws URISyntaxException
* If the resulting URI is invalid.
*/
public static URI rewriteURI(
final URI uri,
final HttpHost target,
final boolean dropFragment) throws URISyntaxException {
Args.notNull(uri, "URI");
if (uri.isOpaque()) {
return uri;
}
final URIBuilder uribuilder = new URIBuilder(uri);
if (target != null) {
uribuilder.setScheme(target.getSchemeName());
uribuilder.setHost(target.getHostName());
uribuilder.setPort(target.getPort());
} else {
uribuilder.setScheme(null);
uribuilder.setHost(null);
uribuilder.setPort(-1);
}
if (dropFragment) {
uribuilder.setFragment(null);
}
if (TextUtils.isEmpty(uribuilder.getPath())) {
uribuilder.setPath("/");
}
return uribuilder.build();
}
/**
* A convenience method for
* {@link URIUtilsHC4#rewriteURI(URI, HttpHost, boolean)} that always keeps the
* fragment.
*/
public static URI rewriteURI(
final URI uri,
final HttpHost target) throws URISyntaxException {
return rewriteURI(uri, target, false);
}
/**
* A convenience method that creates a new {@link URI} whose scheme, host, port, path,
* query are taken from the existing URI, dropping any fragment or user-information.
* The path is set to "/" if not explicitly specified. The existing URI is returned
* unmodified if it has no fragment or user-information and has a path.
*
* @param uri
* original URI.
* @throws URISyntaxException
* If the resulting URI is invalid.
*/
public static URI rewriteURI(final URI uri) throws URISyntaxException {
Args.notNull(uri, "URI");
if (uri.isOpaque()) {
return uri;
}
final URIBuilder uribuilder = new URIBuilder(uri);
if (uribuilder.getUserInfo() != null) {
uribuilder.setUserInfo(null);
}
if (TextUtils.isEmpty(uribuilder.getPath())) {
uribuilder.setPath("/");
}
if (uribuilder.getHost() != null) {
uribuilder.setHost(uribuilder.getHost().toLowerCase(Locale.ENGLISH));
}
uribuilder.setFragment(null);
return uribuilder.build();
}
/**
* Resolves a URI reference against a base URI. Work-around for bug in
* java.net.URI (<http://bugs.sun.com/bugdatabase/view_bug.do?bug_id=4708535>)
*
* @param baseURI the base URI
* @param reference the URI reference
* @return the resulting URI
*/
public static URI resolve(final URI baseURI, final String reference) {
return URIUtilsHC4.resolve(baseURI, URI.create(reference));
}
/**
* Resolves a URI reference against a base URI. Work-around for bugs in
* java.net.URI (e.g. <http://bugs.sun.com/bugdatabase/view_bug.do?bug_id=4708535>)
*
* @param baseURI the base URI
* @param reference the URI reference
* @return the resulting URI
*/
public static URI resolve(final URI baseURI, final URI reference){
Args.notNull(baseURI, "Base URI");
Args.notNull(reference, "Reference URI");
URI ref = reference;
final String s = ref.toString();
if (s.startsWith("?")) {
return resolveReferenceStartingWithQueryString(baseURI, ref);
}
final boolean emptyReference = s.length() == 0;
if (emptyReference) {
ref = URI.create("#");
}
URI resolved = baseURI.resolve(ref);
if (emptyReference) {
final String resolvedString = resolved.toString();
resolved = URI.create(resolvedString.substring(0,
resolvedString.indexOf('#')));
}
return normalizeSyntax(resolved);
}
/**
* Resolves a reference starting with a query string.
*
* @param baseURI the base URI
* @param reference the URI reference starting with a query string
* @return the resulting URI
*/
private static URI resolveReferenceStartingWithQueryString(
final URI baseURI, final URI reference) {
String baseUri = baseURI.toString();
baseUri = baseUri.indexOf('?') > -1 ?
baseUri.substring(0, baseUri.indexOf('?')) : baseUri;
return URI.create(baseUri + reference.toString());
}
/**
* Removes dot segments according to RFC 3986, section 5.2.4 and
* Syntax-Based Normalization according to RFC 3986, section 6.2.2.
*
* @param uri the original URI
* @return the URI without dot segments
*/
private static URI normalizeSyntax(final URI uri) {
if (uri.isOpaque() || uri.getAuthority() == null) {
// opaque and file: URIs
return uri;
}
Args.check(uri.isAbsolute(), "Base URI must be absolute");
final String path = uri.getPath() == null ? "" : uri.getPath();
final String[] inputSegments = path.split("/");
final Stack<String> outputSegments = new Stack<String>();
for (final String inputSegment : inputSegments) {
if ((inputSegment.length() == 0)
|| (".".equals(inputSegment))) {
// Do nothing
} else if ("..".equals(inputSegment)) {
if (!outputSegments.isEmpty()) {
outputSegments.pop();
}
} else {
outputSegments.push(inputSegment);
}
}
final StringBuilder outputBuffer = new StringBuilder();
for (final String outputSegment : outputSegments) {
outputBuffer.append('/').append(outputSegment);
}
if (path.lastIndexOf('/') == path.length() - 1) {
// path.endsWith("/") || path.equals("")
outputBuffer.append('/');
}
try {
final String scheme = uri.getScheme().toLowerCase(Locale.ENGLISH);
final String auth = uri.getAuthority().toLowerCase(Locale.ENGLISH);
final URI ref = new URI(scheme, auth, outputBuffer.toString(),
null, null);
if (uri.getQuery() == null && uri.getFragment() == null) {
return ref;
}
final StringBuilder normalized = new StringBuilder(
ref.toASCIIString());
if (uri.getQuery() != null) {
// query string passed through unchanged
normalized.append('?').append(uri.getRawQuery());
}
if (uri.getFragment() != null) {
// fragment passed through unchanged
normalized.append('#').append(uri.getRawFragment());
}
return URI.create(normalized.toString());
} catch (final URISyntaxException e) {
throw new IllegalArgumentException(e);
}
}
/**
* Extracts target host from the given {@link URI}.
*
* @param uri
* @return the target host if the URI is absolute or <code>null</null> if the URI is
* relative or does not contain a valid host name.
*
* @since 4.1
*/
public static HttpHost extractHost(final URI uri) {
if (uri == null) {
return null;
}
HttpHost target = null;
if (uri.isAbsolute()) {
int port = uri.getPort(); // may be overridden later
String host = uri.getHost();
if (host == null) { // normal parse failed; let's do it ourselves
// authority does not seem to care about the valid character-set for host names
host = uri.getAuthority();
if (host != null) {
// Strip off any leading user credentials
final int at = host.indexOf('@');
if (at >= 0) {
if (host.length() > at+1 ) {
host = host.substring(at+1);
} else {
host = null; // @ on its own
}
}
// Extract the port suffix, if present
if (host != null) {
final int colon = host.indexOf(':');
if (colon >= 0) {
final int pos = colon + 1;
int len = 0;
for (int i = pos; i < host.length(); i++) {
if (Character.isDigit(host.charAt(i))) {
len++;
} else {
break;
}
}
if (len > 0) {
try {
port = Integer.parseInt(host.substring(pos, pos + len));
} catch (final NumberFormatException ex) {
}
}
host = host.substring(0, colon);
}
}
}
}
final String scheme = uri.getScheme();
if (!TextUtils.isBlank(host)) {
target = new HttpHost(host, port, scheme);
}
}
return target;
}
/**
* Derives the interpreted (absolute) URI that was used to generate the last
* request. This is done by extracting the request-uri and target origin for
* the last request and scanning all the redirect locations for the last
* fragment identifier, then combining the result into a {@link URI}.
*
* @param originalURI
* original request before any redirects
* @param target
* if the last URI is relative, it is resolved against this target,
* or <code>null</code> if not available.
* @param redirects
* collection of redirect locations since the original request
* or <code>null</code> if not available.
* @return interpreted (absolute) URI
*/
public static URI resolve(
final URI originalURI,
final HttpHost target,
final List<URI> redirects) throws URISyntaxException {
Args.notNull(originalURI, "Request URI");
final URIBuilder uribuilder;
if (redirects == null || redirects.isEmpty()) {
uribuilder = new URIBuilder(originalURI);
} else {
uribuilder = new URIBuilder(redirects.get(redirects.size() - 1));
String frag = uribuilder.getFragment();
// read interpreted fragment identifier from redirect locations
for (int i = redirects.size() - 1; frag == null && i >= 0; i--) {
frag = redirects.get(i).getFragment();
}
uribuilder.setFragment(frag);
}
// read interpreted fragment identifier from original request
if (uribuilder.getFragment() == null) {
uribuilder.setFragment(originalURI.getFragment());
}
// last target origin
if (target != null && !uribuilder.isAbsolute()) {
uribuilder.setScheme(target.getSchemeName());
uribuilder.setHost(target.getHostName());
uribuilder.setPort(target.getPort());
}
return uribuilder.build();
}
/**
* This class should not be instantiated.
*/
private URIUtilsHC4() {
}
}

View File

@ -1,628 +0,0 @@
/*
* ====================================================================
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you under the Apache License, Version 2.0 (the
* "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
* KIND, either express or implied. See the License for the
* specific language governing permissions and limitations
* under the License.
* ====================================================================
*
* This software consists of voluntary contributions made by many
* individuals on behalf of the Apache Software Foundation. For more
* information on the Apache Software Foundation, please see
* <http://www.apache.org/>.
*
*/
package org.apache.http.client.utils;
import java.io.IOException;
import java.net.URI;
import java.nio.ByteBuffer;
import java.nio.CharBuffer;
import java.nio.charset.Charset;
import java.util.ArrayList;
import java.util.BitSet;
import java.util.Collections;
import java.util.List;
import java.util.Scanner;
import org.apache.http.Consts;
import org.apache.http.Header;
import org.apache.http.HeaderElement;
import org.apache.http.HttpEntity;
import org.apache.http.NameValuePair;
import org.apache.http.annotation.Immutable;
import org.apache.http.entity.ContentType;
import org.apache.http.message.BasicHeaderValueParserHC4;
import org.apache.http.message.BasicNameValuePair;
import org.apache.http.message.ParserCursor;
import org.apache.http.protocol.HTTP;
import org.apache.http.util.CharArrayBuffer;
import org.apache.http.util.EntityUtilsHC4;
/**
* A collection of utilities for encoding URLs.
*
* @since 4.0
*/
@Immutable
public class URLEncodedUtilsHC4 {
/**
* The default HTML form content type.
*/
public static final String CONTENT_TYPE = "application/x-www-form-urlencoded";
private static final char QP_SEP_A = '&';
private static final char QP_SEP_S = ';';
private static final String NAME_VALUE_SEPARATOR = "=";
/**
* Returns a list of {@link NameValuePair NameValuePairs} as built from the URI's query portion. For example, a URI
* of http://example.org/path/to/file?a=1&b=2&c=3 would return a list of three NameValuePairs, one for a=1, one for
* b=2, and one for c=3. By convention, {@code '&'} and {@code ';'} are accepted as parameter separators.
* <p>
* This is typically useful while parsing an HTTP PUT.
*
* This API is currently only used for testing.
*
* @param uri
* URI to parse
* @param charset
* Charset name to use while parsing the query
* @return a list of {@link NameValuePair} as built from the URI's query portion.
*/
public static List <NameValuePair> parse(final URI uri, final String charset) {
final String query = uri.getRawQuery();
if (query != null && query.length() > 0) {
final List<NameValuePair> result = new ArrayList<NameValuePair>();
final Scanner scanner = new Scanner(query);
parse(result, scanner, QP_SEP_PATTERN, charset);
return result;
}
return Collections.emptyList();
}
/**
* Returns a list of {@link NameValuePair NameValuePairs} as parsed from an {@link HttpEntity}. The encoding is
* taken from the entity's Content-Encoding header.
* <p>
* This is typically used while parsing an HTTP POST.
*
* @param entity
* The entity to parse
* @return a list of {@link NameValuePair} as built from the URI's query portion.
* @throws IOException
* If there was an exception getting the entity's data.
*/
public static List <NameValuePair> parse(
final HttpEntity entity) throws IOException {
final ContentType contentType = ContentType.get(entity);
if (contentType != null && contentType.getMimeType().equalsIgnoreCase(CONTENT_TYPE)) {
final String content = EntityUtilsHC4.toString(entity, Consts.ASCII);
if (content != null && content.length() > 0) {
Charset charset = contentType.getCharset();
if (charset == null) {
charset = Charset.forName(HTTP.DEFAULT_CONTENT_CHARSET);
}
return parse(content, charset, QP_SEPS);
}
}
return Collections.emptyList();
}
/**
* Returns true if the entity's Content-Type header is
* <code>application/x-www-form-urlencoded</code>.
*/
public static boolean isEncoded(final HttpEntity entity) {
final Header h = entity.getContentType();
if (h != null) {
final HeaderElement[] elems = h.getElements();
if (elems.length > 0) {
final String contentType = elems[0].getName();
return contentType.equalsIgnoreCase(CONTENT_TYPE);
}
}
return false;
}
/**
* Adds all parameters within the Scanner to the list of <code>parameters</code>, as encoded by
* <code>encoding</code>. For example, a scanner containing the string <code>a=1&b=2&c=3</code> would add the
* {@link NameValuePair NameValuePairs} a=1, b=2, and c=3 to the list of parameters. By convention, {@code '&'} and
* {@code ';'} are accepted as parameter separators.
*
* @param parameters
* List to add parameters to.
* @param scanner
* Input that contains the parameters to parse.
* @param charset
* Encoding to use when decoding the parameters.
*/
public static void parse(
final List <NameValuePair> parameters,
final Scanner scanner,
final String charset) {
parse(parameters, scanner, QP_SEP_PATTERN, charset);
}
/**
* Adds all parameters within the Scanner to the list of
* <code>parameters</code>, as encoded by <code>encoding</code>. For
* example, a scanner containing the string <code>a=1&b=2&c=3</code> would
* add the {@link NameValuePair NameValuePairs} a=1, b=2, and c=3 to the
* list of parameters.
*
* @param parameters
* List to add parameters to.
* @param scanner
* Input that contains the parameters to parse.
* @param parameterSepartorPattern
* The Pattern string for parameter separators, by convention {@code "[&;]"}
* @param charset
* Encoding to use when decoding the parameters.
*/
public static void parse(
final List <NameValuePair> parameters,
final Scanner scanner,
final String parameterSepartorPattern,
final String charset) {
scanner.useDelimiter(parameterSepartorPattern);
while (scanner.hasNext()) {
String name = null;
String value = null;
final String token = scanner.next();
final int i = token.indexOf(NAME_VALUE_SEPARATOR);
if (i != -1) {
name = decodeFormFields(token.substring(0, i).trim(), charset);
value = decodeFormFields(token.substring(i + 1).trim(), charset);
} else {
name = decodeFormFields(token.trim(), charset);
}
parameters.add(new BasicNameValuePair(name, value));
}
}
/**
* Query parameter separators.
*/
private static final char[] QP_SEPS = new char[] { QP_SEP_A, QP_SEP_S };
/**
* Query parameter separator pattern.
*/
private static final String QP_SEP_PATTERN = "[" + new String(QP_SEPS) + "]";
/**
* Returns a list of {@link NameValuePair NameValuePairs} as parsed from the given string using the given character
* encoding. By convention, {@code '&'} and {@code ';'} are accepted as parameter separators.
*
* @param s
* text to parse.
* @param charset
* Encoding to use when decoding the parameters.
* @return a list of {@link NameValuePair} as built from the URI's query portion.
*
* @since 4.2
*/
public static List<NameValuePair> parse(final String s, final Charset charset) {
return parse(s, charset, QP_SEPS);
}
/**
* Returns a list of {@link NameValuePair NameValuePairs} as parsed from the given string using the given character
* encoding.
*
* @param s
* text to parse.
* @param charset
* Encoding to use when decoding the parameters.
* @param parameterSeparator
* The characters used to separate parameters, by convention, {@code '&'} and {@code ';'}.
* @return a list of {@link NameValuePair} as built from the URI's query portion.
*
* @since 4.3
*/
public static List<NameValuePair> parse(final String s, final Charset charset, final char... parameterSeparator) {
if (s == null) {
return Collections.emptyList();
}
final BasicHeaderValueParserHC4 parser = BasicHeaderValueParserHC4.INSTANCE;
final CharArrayBuffer buffer = new CharArrayBuffer(s.length());
buffer.append(s);
final ParserCursor cursor = new ParserCursor(0, buffer.length());
final List<NameValuePair> list = new ArrayList<NameValuePair>();
while (!cursor.atEnd()) {
final NameValuePair nvp = parser.parseNameValuePair(buffer, cursor, parameterSeparator);
if (nvp.getName().length() > 0) {
list.add(new BasicNameValuePair(
decodeFormFields(nvp.getName(), charset),
decodeFormFields(nvp.getValue(), charset)));
}
}
return list;
}
/**
* Returns a String that is suitable for use as an {@code application/x-www-form-urlencoded}
* list of parameters in an HTTP PUT or HTTP POST.
*
* @param parameters The parameters to include.
* @param charset The encoding to use.
* @return An {@code application/x-www-form-urlencoded} string
*/
public static String format(
final List <? extends NameValuePair> parameters,
final String charset) {
return format(parameters, QP_SEP_A, charset);
}
/**
* Returns a String that is suitable for use as an {@code application/x-www-form-urlencoded}
* list of parameters in an HTTP PUT or HTTP POST.
*
* @param parameters The parameters to include.
* @param parameterSeparator The parameter separator, by convention, {@code '&'} or {@code ';'}.
* @param charset The encoding to use.
* @return An {@code application/x-www-form-urlencoded} string
*
* @since 4.3
*/
public static String format(
final List <? extends NameValuePair> parameters,
final char parameterSeparator,
final String charset) {
final StringBuilder result = new StringBuilder();
for (final NameValuePair parameter : parameters) {
final String encodedName = encodeFormFields(parameter.getName(), charset);
final String encodedValue = encodeFormFields(parameter.getValue(), charset);
if (result.length() > 0) {
result.append(parameterSeparator);
}
result.append(encodedName);
if (encodedValue != null) {
result.append(NAME_VALUE_SEPARATOR);
result.append(encodedValue);
}
}
return result.toString();
}
/**
* Returns a String that is suitable for use as an {@code application/x-www-form-urlencoded}
* list of parameters in an HTTP PUT or HTTP POST.
*
* @param parameters The parameters to include.
* @param charset The encoding to use.
* @return An {@code application/x-www-form-urlencoded} string
*
* @since 4.2
*/
public static String format(
final Iterable<? extends NameValuePair> parameters,
final Charset charset) {
return format(parameters, QP_SEP_A, charset);
}
/**
* Returns a String that is suitable for use as an {@code application/x-www-form-urlencoded}
* list of parameters in an HTTP PUT or HTTP POST.
*
* @param parameters The parameters to include.
* @param parameterSeparator The parameter separator, by convention, {@code '&'} or {@code ';'}.
* @param charset The encoding to use.
* @return An {@code application/x-www-form-urlencoded} string
*
* @since 4.3
*/
public static String format(
final Iterable<? extends NameValuePair> parameters,
final char parameterSeparator,
final Charset charset) {
final StringBuilder result = new StringBuilder();
for (final NameValuePair parameter : parameters) {
final String encodedName = encodeFormFields(parameter.getName(), charset);
final String encodedValue = encodeFormFields(parameter.getValue(), charset);
if (result.length() > 0) {
result.append(parameterSeparator);
}
result.append(encodedName);
if (encodedValue != null) {
result.append(NAME_VALUE_SEPARATOR);
result.append(encodedValue);
}
}
return result.toString();
}
/**
* Unreserved characters, i.e. alphanumeric, plus: {@code _ - ! . ~ ' ( ) *}
* <p>
* This list is the same as the {@code unreserved} list in
* <a href="http://www.ietf.org/rfc/rfc2396.txt">RFC 2396</a>
*/
private static final BitSet UNRESERVED = new BitSet(256);
/**
* Punctuation characters: , ; : $ & + =
* <p>
* These are the additional characters allowed by userinfo.
*/
private static final BitSet PUNCT = new BitSet(256);
/** Characters which are safe to use in userinfo,
* i.e. {@link #UNRESERVED} plus {@link #PUNCT}uation */
private static final BitSet USERINFO = new BitSet(256);
/** Characters which are safe to use in a path,
* i.e. {@link #UNRESERVED} plus {@link #PUNCT}uation plus / @ */
private static final BitSet PATHSAFE = new BitSet(256);
/** Characters which are safe to use in a query or a fragment,
* i.e. {@link #RESERVED} plus {@link #UNRESERVED} */
private static final BitSet URIC = new BitSet(256);
/**
* Reserved characters, i.e. {@code ;/?:@&=+$,[]}
* <p>
* This list is the same as the {@code reserved} list in
* <a href="http://www.ietf.org/rfc/rfc2396.txt">RFC 2396</a>
* as augmented by
* <a href="http://www.ietf.org/rfc/rfc2732.txt">RFC 2732</a>
*/
private static final BitSet RESERVED = new BitSet(256);
/**
* Safe characters for x-www-form-urlencoded data, as per java.net.URLEncoder and browser behaviour,
* i.e. alphanumeric plus {@code "-", "_", ".", "*"}
*/
private static final BitSet URLENCODER = new BitSet(256);
static {
// unreserved chars
// alpha characters
for (int i = 'a'; i <= 'z'; i++) {
UNRESERVED.set(i);
}
for (int i = 'A'; i <= 'Z'; i++) {
UNRESERVED.set(i);
}
// numeric characters
for (int i = '0'; i <= '9'; i++) {
UNRESERVED.set(i);
}
UNRESERVED.set('_'); // these are the charactes of the "mark" list
UNRESERVED.set('-');
UNRESERVED.set('.');
UNRESERVED.set('*');
URLENCODER.or(UNRESERVED); // skip remaining unreserved characters
UNRESERVED.set('!');
UNRESERVED.set('~');
UNRESERVED.set('\'');
UNRESERVED.set('(');
UNRESERVED.set(')');
// punct chars
PUNCT.set(',');
PUNCT.set(';');
PUNCT.set(':');
PUNCT.set('$');
PUNCT.set('&');
PUNCT.set('+');
PUNCT.set('=');
// Safe for userinfo
USERINFO.or(UNRESERVED);
USERINFO.or(PUNCT);
// URL path safe
PATHSAFE.or(UNRESERVED);
PATHSAFE.set('/'); // segment separator
PATHSAFE.set(';'); // param separator
PATHSAFE.set(':'); // rest as per list in 2396, i.e. : @ & = + $ ,
PATHSAFE.set('@');
PATHSAFE.set('&');
PATHSAFE.set('=');
PATHSAFE.set('+');
PATHSAFE.set('$');
PATHSAFE.set(',');
RESERVED.set(';');
RESERVED.set('/');
RESERVED.set('?');
RESERVED.set(':');
RESERVED.set('@');
RESERVED.set('&');
RESERVED.set('=');
RESERVED.set('+');
RESERVED.set('$');
RESERVED.set(',');
RESERVED.set('['); // added by RFC 2732
RESERVED.set(']'); // added by RFC 2732
URIC.or(RESERVED);
URIC.or(UNRESERVED);
}
private static final int RADIX = 16;
private static String urlEncode(
final String content,
final Charset charset,
final BitSet safechars,
final boolean blankAsPlus) {
if (content == null) {
return null;
}
final StringBuilder buf = new StringBuilder();
final ByteBuffer bb = charset.encode(content);
while (bb.hasRemaining()) {
final int b = bb.get() & 0xff;
if (safechars.get(b)) {
buf.append((char) b);
} else if (blankAsPlus && b == ' ') {
buf.append('+');
} else {
buf.append("%");
final char hex1 = Character.toUpperCase(Character.forDigit((b >> 4) & 0xF, RADIX));
final char hex2 = Character.toUpperCase(Character.forDigit(b & 0xF, RADIX));
buf.append(hex1);
buf.append(hex2);
}
}
return buf.toString();
}
/**
* Decode/unescape a portion of a URL, to use with the query part ensure {@code plusAsBlank} is true.
*
* @param content the portion to decode
* @param charset the charset to use
* @param plusAsBlank if {@code true}, then convert '+' to space (e.g. for www-url-form-encoded content), otherwise leave as is.
* @return encoded string
*/
private static String urlDecode(
final String content,
final Charset charset,
final boolean plusAsBlank) {
if (content == null) {
return null;
}
final ByteBuffer bb = ByteBuffer.allocate(content.length());
final CharBuffer cb = CharBuffer.wrap(content);
while (cb.hasRemaining()) {
final char c = cb.get();
if (c == '%' && cb.remaining() >= 2) {
final char uc = cb.get();
final char lc = cb.get();
final int u = Character.digit(uc, 16);
final int l = Character.digit(lc, 16);
if (u != -1 && l != -1) {
bb.put((byte) ((u << 4) + l));
} else {
bb.put((byte) '%');
bb.put((byte) uc);
bb.put((byte) lc);
}
} else if (plusAsBlank && c == '+') {
bb.put((byte) ' ');
} else {
bb.put((byte) c);
}
}
bb.flip();
return charset.decode(bb).toString();
}
/**
* Decode/unescape www-url-form-encoded content.
*
* @param content the content to decode, will decode '+' as space
* @param charset the charset to use
* @return encoded string
*/
private static String decodeFormFields (final String content, final String charset) {
if (content == null) {
return null;
}
return urlDecode(content, charset != null ? Charset.forName(charset) : Consts.UTF_8, true);
}
/**
* Decode/unescape www-url-form-encoded content.
*
* @param content the content to decode, will decode '+' as space
* @param charset the charset to use
* @return encoded string
*/
private static String decodeFormFields (final String content, final Charset charset) {
if (content == null) {
return null;
}
return urlDecode(content, charset != null ? charset : Consts.UTF_8, true);
}
/**
* Encode/escape www-url-form-encoded content.
* <p>
* Uses the {@link #URLENCODER} set of characters, rather than
* the {@link #UNRSERVED} set; this is for compatibilty with previous
* releases, URLEncoder.encode() and most browsers.
*
* @param content the content to encode, will convert space to '+'
* @param charset the charset to use
* @return encoded string
*/
private static String encodeFormFields(final String content, final String charset) {
if (content == null) {
return null;
}
return urlEncode(content, charset != null ? Charset.forName(charset) : Consts.UTF_8, URLENCODER, true);
}
/**
* Encode/escape www-url-form-encoded content.
* <p>
* Uses the {@link #URLENCODER} set of characters, rather than
* the {@link #UNRSERVED} set; this is for compatibilty with previous
* releases, URLEncoder.encode() and most browsers.
*
* @param content the content to encode, will convert space to '+'
* @param charset the charset to use
* @return encoded string
*/
private static String encodeFormFields (final String content, final Charset charset) {
if (content == null) {
return null;
}
return urlEncode(content, charset != null ? charset : Consts.UTF_8, URLENCODER, true);
}
/**
* Encode a String using the {@link #USERINFO} set of characters.
* <p>
* Used by URIBuilder to encode the userinfo segment.
*
* @param content the string to encode, does not convert space to '+'
* @param charset the charset to use
* @return the encoded string
*/
static String encUserInfo(final String content, final Charset charset) {
return urlEncode(content, charset, USERINFO, false);
}
/**
* Encode a String using the {@link #URIC} set of characters.
* <p>
* Used by URIBuilder to encode the query and fragment segments.
*
* @param content the string to encode, does not convert space to '+'
* @param charset the charset to use
* @return the encoded string
*/
static String encUric(final String content, final Charset charset) {
return urlEncode(content, charset, URIC, false);
}
/**
* Encode a String using the {@link #PATHSAFE} set of characters.
* <p>
* Used by URIBuilder to encode path segments.
*
* @param content the string to encode, does not convert space to '+'
* @param charset the charset to use
* @return the encoded string
*/
static String encPath(final String content, final Charset charset) {
return urlEncode(content, charset, PATHSAFE, false);
}
}

View File

@ -1,31 +0,0 @@
/*
* ====================================================================
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you under the Apache License, Version 2.0 (the
* "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
* KIND, either express or implied. See the License for the
* specific language governing permissions and limitations
* under the License.
* ====================================================================
*
* This software consists of voluntary contributions made by many
* individuals on behalf of the Apache Software Foundation. For more
* information on the Apache Software Foundation, please see
* <http://www.apache.org/>.
*
*/
/**
* Client utility classes.
*/
package org.apache.http.client.utils;

View File

@ -1,154 +0,0 @@
/*
* ====================================================================
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you under the Apache License, Version 2.0 (the
* "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
* KIND, either express or implied. See the License for the
* specific language governing permissions and limitations
* under the License.
* ====================================================================
*
* This software consists of voluntary contributions made by many
* individuals on behalf of the Apache Software Foundation. For more
* information on the Apache Software Foundation, please see
* <http://www.apache.org/>.
*
*/
package org.apache.http.concurrent;
import org.apache.http.util.Args;
import java.util.concurrent.ExecutionException;
import java.util.concurrent.Future;
import java.util.concurrent.TimeUnit;
import java.util.concurrent.TimeoutException;
/**
* Basic implementation of the {@link Future} interface. <tt>BasicFuture<tt>
* can be put into a completed state by invoking any of the following methods:
* {@link #cancel()}, {@link #failed(Exception)}, or {@link #completed(Object)}.
*
* @param <T> the future result type of an asynchronous operation.
* @since 4.2
*/
public class BasicFuture<T> implements Future<T>, Cancellable {
private final FutureCallback<T> callback;
private volatile boolean completed;
private volatile boolean cancelled;
private volatile T result;
private volatile Exception ex;
public BasicFuture(final FutureCallback<T> callback) {
super();
this.callback = callback;
}
public boolean isCancelled() {
return this.cancelled;
}
public boolean isDone() {
return this.completed;
}
private T getResult() throws ExecutionException {
if (this.ex != null) {
throw new ExecutionException(this.ex);
}
return this.result;
}
public synchronized T get() throws InterruptedException, ExecutionException {
while (!this.completed) {
wait();
}
return getResult();
}
public synchronized T get(final long timeout, final TimeUnit unit)
throws InterruptedException, ExecutionException, TimeoutException {
Args.notNull(unit, "Time unit");
final long msecs = unit.toMillis(timeout);
final long startTime = (msecs <= 0) ? 0 : System.currentTimeMillis();
long waitTime = msecs;
if (this.completed) {
return getResult();
} else if (waitTime <= 0) {
throw new TimeoutException();
} else {
for (;;) {
wait(waitTime);
if (this.completed) {
return getResult();
} else {
waitTime = msecs - (System.currentTimeMillis() - startTime);
if (waitTime <= 0) {
throw new TimeoutException();
}
}
}
}
}
public boolean completed(final T result) {
synchronized(this) {
if (this.completed) {
return false;
}
this.completed = true;
this.result = result;
notifyAll();
}
if (this.callback != null) {
this.callback.completed(result);
}
return true;
}
public boolean failed(final Exception exception) {
synchronized(this) {
if (this.completed) {
return false;
}
this.completed = true;
this.ex = exception;
notifyAll();
}
if (this.callback != null) {
this.callback.failed(exception);
}
return true;
}
public boolean cancel(final boolean mayInterruptIfRunning) {
synchronized(this) {
if (this.completed) {
return false;
}
this.completed = true;
this.cancelled = true;
notifyAll();
}
if (this.callback != null) {
this.callback.cancelled();
}
return true;
}
public boolean cancel() {
return cancel(true);
}
}

View File

@ -1,39 +0,0 @@
/*
* ====================================================================
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you under the Apache License, Version 2.0 (the
* "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
* KIND, either express or implied. See the License for the
* specific language governing permissions and limitations
* under the License.
* ====================================================================
*
* This software consists of voluntary contributions made by many
* individuals on behalf of the Apache Software Foundation. For more
* information on the Apache Software Foundation, please see
* <http://www.apache.org/>.
*
*/
package org.apache.http.concurrent;
/**
* A <tt>Cancellable</tt> represents a process or an operation that can be
* canceled.
*
* @since 4.2
*/
public interface Cancellable {
boolean cancel();
}

Some files were not shown because too many files have changed in this diff Show More