下面列出了java.net.HttpURLConnection#HTTP_PARTIAL 实例代码,或者点击链接到github查看源代码,也可以在右侧发表评论。
public void testRequestWasSuccessful_unsuccessfulStatusCodes() {
// 204 and 205 are considered unsuccessful in this case, and 206 should never happen. Also
// test with some of the other common status codes (these are ones that our backend has
// been known to return).
final int[] statusCodes = {
HttpURLConnection.HTTP_NO_CONTENT,
HttpURLConnection.HTTP_RESET,
HttpURLConnection.HTTP_PARTIAL,
HttpURLConnection.HTTP_BAD_REQUEST,
HttpURLConnection.HTTP_UNAUTHORIZED,
HttpURLConnection.HTTP_FORBIDDEN,
HttpURLConnection.HTTP_NOT_FOUND,
HttpURLConnection.HTTP_NOT_ACCEPTABLE,
HttpURLConnection.HTTP_INTERNAL_ERROR,
HttpURLConnection.HTTP_BAD_GATEWAY,
HttpURLConnection.HTTP_UNAVAILABLE,
HttpURLConnection.HTTP_GATEWAY_TIMEOUT
};
for (int statusCode : statusCodes) {
assertFalse(defaultSettingsSpiCall.requestWasSuccessful(statusCode));
}
}
/** Use HTTP Range header for specifying offset. */
@Override
protected HttpURLConnection connect(final long offset,
final boolean resolved) throws IOException {
final HttpURLConnection conn = openConnection();
conn.setRequestMethod("GET");
if (offset != 0L) {
conn.setRequestProperty("Range", "bytes=" + offset + "-");
}
conn.connect();
//Expects HTTP_OK or HTTP_PARTIAL response codes.
final int code = conn.getResponseCode();
if (offset != 0L && code != HttpURLConnection.HTTP_PARTIAL) {
throw new IOException("HTTP_PARTIAL expected, received " + code);
} else if (offset == 0L && code != HttpURLConnection.HTTP_OK) {
throw new IOException("HTTP_OK expected, received " + code);
}
return conn;
}
/** Use HTTP Range header for specifying offset. */
@Override
protected HttpURLConnection connect(final long offset,
final boolean resolved) throws IOException {
final HttpURLConnection conn = openConnection();
conn.setRequestMethod("GET");
if (offset != 0L) {
conn.setRequestProperty("Range", "bytes=" + offset + "-");
}
conn.connect();
//Expects HTTP_OK or HTTP_PARTIAL response codes.
final int code = conn.getResponseCode();
if (offset != 0L && code != HttpURLConnection.HTTP_PARTIAL) {
throw new IOException("HTTP_PARTIAL expected, received " + code);
} else if (offset == 0L && code != HttpURLConnection.HTTP_OK) {
throw new IOException("HTTP_OK expected, received " + code);
}
return conn;
}
public static boolean isSupportRange(String fileUrl, String[] headers) throws MalformedURLException {
int times = 2;
URL url = new URL(fileUrl);
HttpURLConnection conn = null;
int code;
while (times-- > 0) {
try {
conn = openConnection(url);
conn.setUseCaches(false);
conn.setRequestProperty("Range", "bytes=0-0");
fillHeaders(conn, headers);
conn.setInstanceFollowRedirects(true);
HttpURLConnection.setFollowRedirects(true);
conn.setConnectTimeout(2000);
conn.setReadTimeout(1000);
conn.connect();
code = conn.getResponseCode();
if (REDIRECTED_CODE.contains(code)) {
fileUrl = conn.getHeaderField("Location");
if (StringUtils.isNotBlank(fileUrl)) {
return isSupportRange(fileUrl, null);
}
}
return code == HttpURLConnection.HTTP_PARTIAL;
} catch (Exception e) {
logger.warn("url:{} isSupportRange error", fileUrl, e);
} finally {
closeConn(conn);
conn = null;
}
}
return false;
}
public boolean isServerCanceled(int responseCode, boolean isAlreadyProceed) {
if (responseCode != HttpURLConnection.HTTP_PARTIAL
&& responseCode != HttpURLConnection.HTTP_OK) {
return true;
}
if (responseCode == HttpURLConnection.HTTP_OK && isAlreadyProceed) {
return true;
}
return false;
}
private static boolean isAcceptRange(@NonNull DownloadConnection.Connected connected)
throws IOException {
if (connected.getResponseCode() == HttpURLConnection.HTTP_PARTIAL) return true;
final String acceptRanges = connected.getResponseHeaderField(ACCEPT_RANGES);
return "bytes".equals(acceptRanges);
}
private void sendMessage(String url, Message msg, MimeBodyPart securedData, String retries) throws Exception {
URL urlObj = new URL(url);
InternetHeaders ih = getHttpHeaders(msg, securedData);
msg.setAttribute(NetAttribute.MA_DESTINATION_IP, urlObj.getHost());
msg.setAttribute(NetAttribute.MA_DESTINATION_PORT, Integer.toString(urlObj.getPort()));
if (logger.isInfoEnabled()) {
logger.info("Connecting to: " + url + msg.getLogMsgID());
}
Map<String, String> httpOptions = getHttpOptions();
httpOptions.put(HTTPUtil.PARAM_HTTP_USER, msg.getPartnership().getAttribute(HTTPUtil.PARAM_HTTP_USER));
httpOptions.put(HTTPUtil.PARAM_HTTP_PWD, msg.getPartnership().getAttribute(HTTPUtil.PARAM_HTTP_PWD));
long maxSize = msg.getPartnership().getNoChunkedMaxSize();
ResponseWrapper resp = HTTPUtil.execRequest(HTTPUtil.Method.POST, url, ih.getAllHeaders(), null, securedData.getInputStream(), httpOptions, maxSize);
if (logger.isInfoEnabled()) {
logger.info("Message sent and response received in " + resp.getTransferTimeMs() + "ms" + msg.getLogMsgID());
}
// Check the HTTP Response code
int rc = resp.getStatusCode();
if ((rc != HttpURLConnection.HTTP_OK) && (rc != HttpURLConnection.HTTP_CREATED) && (rc != HttpURLConnection.HTTP_ACCEPTED) && (rc != HttpURLConnection.HTTP_PARTIAL) && (rc != HttpURLConnection.HTTP_NO_CONTENT)) {
msg.setLogMsg("Error sending message. URL: " + url + " ::: Response Code: " + rc + " " + resp.getStatusPhrase() + " ::: Response Message: " + resp.getBody().toString());
logger.error(msg);
throw new HttpResponseException(url, rc, resp.getStatusPhrase());
}
// So far so good ...
processResponse(msg, resp);
}
public static boolean isAcceptRange(int responseCode, FileDownloadConnection connection) {
if (responseCode == HttpURLConnection.HTTP_PARTIAL
|| responseCode == FileDownloadConnection.RESPONSE_CODE_FROM_OFFSET) return true;
final String acceptRanges = connection.getResponseHeaderField("Accept-Ranges");
return "bytes".equals(acceptRanges);
}
private InputStream readData(int offset, int length) throws IOException{
HttpURLConnection conn = (HttpURLConnection) zipUrl.openConnection();
conn.setDoOutput(false);
conn.setUseCaches(false);
conn.setInstanceFollowRedirects(false);
String range = "-";
if (offset != Integer.MAX_VALUE){
range = offset + range;
}
if (length != Integer.MAX_VALUE){
if (offset != Integer.MAX_VALUE){
range = range + (offset + length - 1);
}else{
range = range + length;
}
}
conn.setRequestProperty("Range", "bytes=" + range);
conn.connect();
if (conn.getResponseCode() == HttpURLConnection.HTTP_PARTIAL){
return conn.getInputStream();
}else if (conn.getResponseCode() == HttpURLConnection.HTTP_OK){
throw new IOException("Your server does not support HTTP feature Content-Range. Please contact your server administrator.");
}else{
throw new IOException(conn.getResponseCode() + " " + conn.getResponseMessage());
}
}
private InputStream readData(int offset, int length) throws IOException{
HttpURLConnection conn = (HttpURLConnection) zipUrl.openConnection();
conn.setDoOutput(false);
conn.setUseCaches(false);
conn.setInstanceFollowRedirects(false);
String range = "-";
if (offset != Integer.MAX_VALUE){
range = offset + range;
}
if (length != Integer.MAX_VALUE){
if (offset != Integer.MAX_VALUE){
range = range + (offset + length - 1);
}else{
range = range + length;
}
}
conn.setRequestProperty("Range", "bytes=" + range);
conn.connect();
if (conn.getResponseCode() == HttpURLConnection.HTTP_PARTIAL){
return conn.getInputStream();
}else if (conn.getResponseCode() == HttpURLConnection.HTTP_OK){
throw new IOException("Your server does not support HTTP feature Content-Range. Please contact your server administrator.");
}else{
throw new IOException(conn.getResponseCode() + " " + conn.getResponseMessage());
}
}
private void setResumeSupportedOrNot() {
isResumeSupported = (responseCode == HttpURLConnection.HTTP_PARTIAL);
}
private boolean sendAsyncMDN(MessageMDN mdn, String url, DispositionType disposition, Map<Object, Object> options) throws OpenAS2Exception {
Message msg = mdn.getMessage();
try {
// Create a HTTP connection
if (logger.isDebugEnabled()) {
logger.debug("ASYNC MDN attempting connection to: " + url + mdn.getMessage().getLogMsgID());
}
long maxSize = msg.getPartnership().getNoChunkedMaxSize();
Map<String, String> httpOptions = getHttpOptions();
httpOptions.put(HTTPUtil.PARAM_HTTP_USER, msg.getPartnership().getAttribute(HTTPUtil.PARAM_HTTP_USER));
httpOptions.put(HTTPUtil.PARAM_HTTP_PWD, msg.getPartnership().getAttribute(HTTPUtil.PARAM_HTTP_PWD));
ResponseWrapper resp = HTTPUtil.execRequest(HTTPUtil.Method.POST, url, mdn.getHeaders().getAllHeaders(), null, mdn.getData().getInputStream(), httpOptions, maxSize);
int respCode = resp.getStatusCode();
// Check the HTTP Response code
if ((respCode != HttpURLConnection.HTTP_OK) && (respCode != HttpURLConnection.HTTP_CREATED) && (respCode != HttpURLConnection.HTTP_ACCEPTED) && (respCode != HttpURLConnection.HTTP_PARTIAL) && (respCode != HttpURLConnection.HTTP_NO_CONTENT)) {
if (logger.isErrorEnabled()) {
msg.setLogMsg("Error sending AsyncMDN [" + disposition.toString() + "] HTTP response code: " + respCode);
logger.error(msg);
}
throw new HttpResponseException(url, respCode, resp.getStatusPhrase());
}
if (logger.isInfoEnabled()) {
logger.info("sent AsyncMDN [" + disposition.toString() + "] OK " + msg.getLogMsgID());
}
// log & store mdn into backup folder.
getSession().getProcessor().handle(StorageModule.DO_STOREMDN, msg, null);
// Log significant msg state
msg.setOption("STATE", Message.MSG_STATE_MSG_RXD_MDN_SENT_OK);
msg.trackMsgState(getSession());
} catch (HttpResponseException hre) {
// Resend if the HTTP Response has an error code
logger.warn("HTTP exception sending ASYNC MDN: " + org.openas2.logging.Log.getExceptionMsg(hre) + msg.getLogMsgID(), hre);
hre.terminate();
resend(msg, hre);
// Log significant msg state
msg.setOption("STATE", Message.MSG_STATE_MDN_SENDING_EXCEPTION);
msg.trackMsgState(getSession());
return false;
} catch (IOException ioe) {
logger.warn("IO exception sending ASYNC MDN: " + org.openas2.logging.Log.getExceptionMsg(ioe) + msg.getLogMsgID(), ioe);
// Resend if a network error occurs during transmission
WrappedException wioe = new WrappedException(ioe);
wioe.addSource(OpenAS2Exception.SOURCE_MESSAGE, msg);
wioe.terminate();
resend(msg, wioe);
// Log significant msg state
msg.setOption("STATE", Message.MSG_STATE_MDN_SENDING_EXCEPTION);
msg.trackMsgState(getSession());
return false;
} catch (Exception e) {
logger.warn("Unexpected exception sending ASYNC MDN: " + org.openas2.logging.Log.getExceptionMsg(e) + msg.getLogMsgID(), e);
// Propagate error if it can't be handled by a resend
// log & store mdn into backup folder.
getSession().getProcessor().handle(StorageModule.DO_STOREMDN, msg, null);
// Log significant msg state
msg.setOption("STATE", Message.MSG_STATE_MDN_SENDING_EXCEPTION);
msg.trackMsgState(getSession());
throw new WrappedException(e);
}
return true;
}
@Override
public void run() {
Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND);
FileDownloadConnection connection = null;
final long beginOffset = connectTask.getProfile().currentOffset;
boolean isConnected = false;
do {
try {
if (paused) {
return;
}
isConnected = false;
connection = connectTask.connect();
final int code = connection.getResponseCode();
if (FileDownloadLog.NEED_LOG) {
FileDownloadLog
.d(this, "the connection[%d] for %d, is connected %s with code[%d]",
connectionIndex, downloadId, connectTask.getProfile(), code);
}
if (code != HttpURLConnection.HTTP_PARTIAL && code != HttpURLConnection.HTTP_OK) {
throw new SocketException(FileDownloadUtils.
formatString(
"Connection failed with request[%s] response[%s] "
+ "http-state[%d] on task[%d-%d], which is changed"
+ " after verify connection, so please try again.",
connectTask.getRequestHeader(),
connection.getResponseHeaderFields(),
code, downloadId, connectionIndex));
}
isConnected = true;
final FetchDataTask.Builder builder = new FetchDataTask.Builder();
if (paused) return;
fetchDataTask = builder
.setDownloadId(downloadId)
.setConnectionIndex(connectionIndex)
.setCallback(callback)
.setHost(this)
.setWifiRequired(isWifiRequired)
.setConnection(connection)
.setConnectionProfile(this.connectTask.getProfile())
.setPath(path)
.build();
fetchDataTask.run();
if (paused) fetchDataTask.pause();
break;
} catch (IllegalAccessException | IOException | FileDownloadGiveUpRetryException
| IllegalArgumentException e) {
if (callback.isRetry(e)) {
if (isConnected && fetchDataTask == null) {
// connected but create fetch data task failed, give up directly.
FileDownloadLog.w(this, "it is valid to retry and connection is valid but"
+ " create fetch-data-task failed, so give up directly with %s", e);
callback.onError(e);
break;
} else {
if (fetchDataTask != null) {
//update currentOffset in ConnectionProfile
final long downloadedOffset = getDownloadedOffset();
if (downloadedOffset > 0) {
connectTask.updateConnectionProfile(downloadedOffset);
}
}
callback.onRetry(e);
}
} else {
callback.onError(e);
break;
}
} finally {
if (connection != null) connection.ending();
}
} while (true);
}
/**
* Map from HTTP status code to reason description.
* Sentry HTTP breadcrumbs expect a text description of the HTTP status-code.
* This function implements a look-up table with a default value for unknown status-codes.
* @param statusCode an integer HTTP status code, expected to be in the range [200,505].
* @return a non-empty string in all cases.
*/
private static String httpReason(int statusCode) {
switch (statusCode) {
// 2xx
case HttpURLConnection.HTTP_OK: return "OK";
case HttpURLConnection.HTTP_CREATED: return "Created";
case HttpURLConnection.HTTP_ACCEPTED: return "Accepted";
case HttpURLConnection.HTTP_NOT_AUTHORITATIVE: return "Non-Authoritative Information";
case HttpURLConnection.HTTP_NO_CONTENT: return "No Content";
case HttpURLConnection.HTTP_RESET: return "Reset Content";
case HttpURLConnection.HTTP_PARTIAL: return "Partial Content";
// 3xx
case HttpURLConnection.HTTP_MULT_CHOICE: return "Multiple Choices";
case HttpURLConnection.HTTP_MOVED_PERM: return "Moved Permanently";
case HttpURLConnection.HTTP_MOVED_TEMP: return "Temporary Redirect";
case HttpURLConnection.HTTP_SEE_OTHER: return "See Other";
case HttpURLConnection.HTTP_NOT_MODIFIED: return "Not Modified";
case HttpURLConnection.HTTP_USE_PROXY: return "Use Proxy";
// 4xx
case HttpURLConnection.HTTP_BAD_REQUEST: return "Bad Request";
case HttpURLConnection.HTTP_UNAUTHORIZED: return "Unauthorized";
case HttpURLConnection.HTTP_PAYMENT_REQUIRED: return "Payment Required";
case HttpURLConnection.HTTP_FORBIDDEN: return "Forbidden";
case HttpURLConnection.HTTP_NOT_FOUND: return "Not Found";
case HttpURLConnection.HTTP_BAD_METHOD: return "Method Not Allowed";
case HttpURLConnection.HTTP_NOT_ACCEPTABLE: return "Not Acceptable";
case HttpURLConnection.HTTP_PROXY_AUTH: return "Proxy Authentication Required";
case HttpURLConnection.HTTP_CLIENT_TIMEOUT: return "Request Time-Out";
case HttpURLConnection.HTTP_CONFLICT: return "Conflict";
case HttpURLConnection.HTTP_GONE: return "Gone";
case HttpURLConnection.HTTP_LENGTH_REQUIRED: return "Length Required";
case HttpURLConnection.HTTP_PRECON_FAILED: return "Precondition Failed";
case HttpURLConnection.HTTP_ENTITY_TOO_LARGE: return "Request Entity Too Large";
case HttpURLConnection.HTTP_REQ_TOO_LONG: return "Request-URI Too Large";
case HttpURLConnection.HTTP_UNSUPPORTED_TYPE: return "Unsupported Media Type";
// 5xx
case HttpURLConnection.HTTP_INTERNAL_ERROR: return "Internal Server Error";
case HttpURLConnection.HTTP_NOT_IMPLEMENTED: return "Not Implemented";
case HttpURLConnection.HTTP_BAD_GATEWAY: return "Bad Gateway";
case HttpURLConnection.HTTP_UNAVAILABLE: return "Service Unavailable";
case HttpURLConnection.HTTP_GATEWAY_TIMEOUT: return "Gateway Timeout";
case HttpURLConnection.HTTP_VERSION: return "Version Not Supported";
default: return "unknown";
}
}