下面列出了怎么用java.net.ProtocolException的API类实例代码及写法,或者点击链接到github查看源代码。
/**
* Handles a redirect.
*
* @param originalUrl The original URL.
* @param location The Location header in the response.
* @return The next URL.
* @throws IOException If redirection isn't possible.
*/
private static URL handleRedirect(URL originalUrl, String location) throws IOException {
if (location == null) {
throw new ProtocolException("Null location redirect");
}
// Form the new url.
URL url = new URL(originalUrl, location);
// Check that the protocol of the new url is supported.
String protocol = url.getProtocol();
if (!"https".equals(protocol) && !"http".equals(protocol)) {
throw new ProtocolException("Unsupported protocol redirect: " + protocol);
}
// Currently this method is only called if allowCrossProtocolRedirects is true, and so the code
// below isn't required. If we ever decide to handle redirects ourselves when cross-protocol
// redirects are disabled, we'll need to uncomment this block of code.
// if (!allowCrossProtocolRedirects && !protocol.equals(originalUrl.getProtocol())) {
// throw new ProtocolException("Disallowed cross-protocol redirect ("
// + originalUrl.getProtocol() + " to " + protocol + ")");
// }
return url;
}
/**
* Allows to call a remote URL in POST mode and pass parameters.
*
* @param url the URL to call
* @param parametersMap the parameters, empty if none. (Cannot be null).
* @return the value returned by the call
*
* @throws IOException if an IOException occurs
* @throws ProtocolException if a ProtocolException occurs
* @throws SocketTimeoutException if a if a ProtocolException occurs
* occurs
* @throws UnsupportedEncodingException if a if a ProtocolException occurs
* occurs
*/
public String callWithPost(URL url, Map<String, String> parametersMap)
throws IOException, ProtocolException, SocketTimeoutException, UnsupportedEncodingException {
if (url == null) {
throw new NullPointerException("url is null!");
}
if (parametersMap == null) {
throw new NullPointerException("parametersMap is null!");
}
String result = null;
try (InputStream in = callWithPostReturnStream(url, parametersMap);) {
if (in != null) {
ByteArrayOutputStream out = new ByteArrayOutputStream();
IOUtils.copy(in, out);
result = out.toString("UTF-8");
trace("result :" + result + ":");
}
}
return result;
}
private void readChunkSize() throws IOException {
// read the suffix of the previous chunk
if (bytesRemainingInChunk != NO_CHUNK_YET) {
Util.readAsciiLine(in);
}
String chunkSizeString = Util.readAsciiLine(in);
int index = chunkSizeString.indexOf(";");
if (index != -1) {
chunkSizeString = chunkSizeString.substring(0, index);
}
try {
bytesRemainingInChunk = Integer.parseInt(chunkSizeString.trim(), 16);
} catch (NumberFormatException e) {
throw new ProtocolException("Expected a hex chunk size but was " + chunkSizeString);
}
if (bytesRemainingInChunk == 0) {
hasMoreChunks = false;
RawHeaders rawResponseHeaders = httpEngine.responseHeaders.getHeaders();
RawHeaders.readHeaders(transport.socketIn, rawResponseHeaders);
httpEngine.receiveHeaders(rawResponseHeaders);
endOfInput();
}
}
private Socket AuthenticateProxy(ConnectMethod method, ProxyClient client,
String proxyHost, int proxyPort,
String proxyUsername, String proxyPassword) throws IOException {
if(method.getProxyAuthState().getAuthScheme().getSchemeName().equalsIgnoreCase("ntlm")) {
// If Auth scheme is NTLM, set NT credentials with blank host and domain name
client.getState().setProxyCredentials(new AuthScope(proxyHost, proxyPort),
new NTCredentials(proxyUsername, proxyPassword,"",""));
} else {
// If Auth scheme is Basic/Digest, set regular Credentials
client.getState().setProxyCredentials(new AuthScope(proxyHost, proxyPort),
new UsernamePasswordCredentials(proxyUsername, proxyPassword));
}
ProxyClient.ConnectResponse response = client.connect();
Socket socket = response.getSocket();
if (socket == null) {
method = response.getConnectMethod();
throw new ProtocolException("Proxy Authentication failed. Socket not created: "
+ method.getStatusLine());
}
return socket;
}
/**
* Handles a redirect.
*
* @param originalUrl The original URL.
* @param location The Location header in the response.
* @return The next URL.
* @throws IOException If redirection isn't possible.
*/
private static URL handleRedirect(URL originalUrl, String location) throws IOException {
if (location == null) {
throw new ProtocolException("Null location redirect");
}
// Form the new url.
URL url = new URL(originalUrl, location);
// Check that the protocol of the new url is supported.
String protocol = url.getProtocol();
if (!"https".equals(protocol) && !"http".equals(protocol)) {
throw new ProtocolException("Unsupported protocol redirect: " + protocol);
}
// Currently this method is only called if allowCrossProtocolRedirects is true, and so the code
// below isn't required. If we ever decide to handle redirects ourselves when cross-protocol
// redirects are disabled, we'll need to uncomment this block of code.
// if (!allowCrossProtocolRedirects && !protocol.equals(originalUrl.getProtocol())) {
// throw new ProtocolException("Disallowed cross-protocol redirect ("
// + originalUrl.getProtocol() + " to " + protocol + ")");
// }
return url;
}
private void readChunkSize() throws IOException {
// read the suffix of the previous chunk
if (bytesRemainingInChunk != NO_CHUNK_YET) {
Util.readAsciiLine(in);
}
String chunkSizeString = Util.readAsciiLine(in);
int index = chunkSizeString.indexOf(";");
if (index != -1) {
chunkSizeString = chunkSizeString.substring(0, index);
}
try {
bytesRemainingInChunk = Integer.parseInt(chunkSizeString.trim(), 16);
} catch (NumberFormatException e) {
throw new ProtocolException("Expected a hex chunk size but was " + chunkSizeString);
}
if (bytesRemainingInChunk == 0) {
hasMoreChunks = false;
RawHeaders rawResponseHeaders = httpEngine.responseHeaders.getHeaders();
RawHeaders.readHeaders(transport.socketIn, rawResponseHeaders);
httpEngine.receiveHeaders(rawResponseHeaders);
endOfInput();
}
}
private void initHttpEngine() throws IOException {
if (httpEngineFailure != null) {
throw httpEngineFailure;
} else if (httpEngine != null) {
return;
}
connected = true;
try {
if (doOutput) {
if (method.equals("GET")) {
// they are requesting a stream to write to. This implies a POST method
method = "POST";
} else if (!method.equals("POST") && !method.equals("PUT") && !method.equals("PATCH")) {
// If the request method is neither POST nor PUT nor PATCH, then you're not writing
throw new ProtocolException(method + " does not support writing");
}
}
httpEngine = newHttpEngine(method, rawRequestHeaders, null, null);
} catch (IOException e) {
httpEngineFailure = e;
throw e;
}
}
private void initHttpEngine() throws IOException {
if (httpEngineFailure != null) {
throw httpEngineFailure;
} else if (httpEngine != null) {
return;
}
connected = true;
try {
if (doOutput) {
if (method.equals("GET")) {
// they are requesting a stream to write to. This implies a POST method
method = "POST";
} else if (!HttpMethod.permitsRequestBody(method)) {
throw new ProtocolException(method + " does not support writing");
}
}
// If the user set content length to zero, we know there will not be a request body.
httpEngine = newHttpEngine(method, null, null, null);
} catch (IOException e) {
httpEngineFailure = e;
throw e;
}
}
private void readChunkSize() throws IOException {
// Read the suffix of the previous chunk.
if (bytesRemainingInChunk != NO_CHUNK_YET) {
source.readUtf8LineStrict();
}
try {
bytesRemainingInChunk = source.readHexadecimalUnsignedLong();
String extensions = source.readUtf8LineStrict().trim();
if (bytesRemainingInChunk < 0 || (!extensions.isEmpty() && !extensions.startsWith(";"))) {
throw new ProtocolException("expected chunk size and optional extensions but was \""
+ bytesRemainingInChunk + extensions + "\"");
}
} catch (NumberFormatException e) {
throw new ProtocolException(e.getMessage());
}
if (bytesRemainingInChunk == 0L) {
hasMoreChunks = false;
HttpHeaders.receiveHeaders(client.cookieJar(), url, readHeaders());
endOfInput(true);
}
}
private void readChunkSize() throws IOException {
// read the suffix of the previous chunk
if (bytesRemainingInChunk != NO_CHUNK_YET) {
Util.readAsciiLine(in);
}
String chunkSizeString = Util.readAsciiLine(in);
int index = chunkSizeString.indexOf(";");
if (index != -1) {
chunkSizeString = chunkSizeString.substring(0, index);
}
try {
bytesRemainingInChunk = Integer.parseInt(chunkSizeString.trim(), 16);
} catch (NumberFormatException e) {
throw new ProtocolException("Expected a hex chunk size but was " + chunkSizeString);
}
if (bytesRemainingInChunk == 0) {
hasMoreChunks = false;
RawHeaders rawResponseHeaders = httpEngine.responseHeaders.getHeaders();
RawHeaders.readHeaders(transport.socketIn, rawResponseHeaders);
httpEngine.receiveHeaders(rawResponseHeaders);
endOfInput(false);
}
}
private void readChunkSize() throws IOException {
// read the suffix of the previous chunk
if (bytesRemainingInChunk != NO_CHUNK_YET) {
Util.readAsciiLine(in);
}
String chunkSizeString = Util.readAsciiLine(in);
int index = chunkSizeString.indexOf(";");
if (index != -1) {
chunkSizeString = chunkSizeString.substring(0, index);
}
try {
bytesRemainingInChunk = Integer.parseInt(chunkSizeString.trim(), 16);
} catch (NumberFormatException e) {
throw new ProtocolException("Expected a hex chunk size but was " + chunkSizeString);
}
if (bytesRemainingInChunk == 0) {
hasMoreChunks = false;
RawHeaders rawResponseHeaders = httpEngine.responseHeaders.getHeaders();
RawHeaders.readHeaders(transport.socketIn, rawResponseHeaders);
httpEngine.receiveHeaders(rawResponseHeaders);
endOfInput();
}
}
void checkResponse(Response response) throws ProtocolException {
if (response.code() != 101) {
throw new ProtocolException("Expected HTTP 101 response but was '"
+ response.code() + " " + response.message() + "'");
}
String headerConnection = response.header("Connection");
if (!"Upgrade".equalsIgnoreCase(headerConnection)) {
throw new ProtocolException("Expected 'Connection' header value 'Upgrade' but was '"
+ headerConnection + "'");
}
String headerUpgrade = response.header("Upgrade");
if (!"websocket".equalsIgnoreCase(headerUpgrade)) {
throw new ProtocolException(
"Expected 'Upgrade' header value 'websocket' but was '" + headerUpgrade + "'");
}
String headerAccept = response.header("Sec-WebSocket-Accept");
String acceptExpected = ByteString.encodeUtf8(key + WebSocketProtocol.ACCEPT_MAGIC)
.sha1().base64();
if (!acceptExpected.equals(headerAccept)) {
throw new ProtocolException("Expected 'Sec-WebSocket-Accept' header value '"
+ acceptExpected + "' but was '" + headerAccept + "'");
}
}
@Override
public void close() throws IOException {
if (closed) {
return;
}
closed = true;
if (bytesRemaining > 0) {
throw new ProtocolException("unexpected end of stream");
}
}
public void setRequestMethod( int requestMethod ){
try {
Constants.REQUEST_METHOD_TYPE obj = Constants.REQUEST_METHOD_TYPE.get( requestMethod );
conn.setRequestMethod(obj.Name());
conn.setDoOutput(obj.DoOutput());
} catch( ProtocolException pe ) {
Log.e(TAG, pe.toString());
}
}
@Override public void close() throws IOException {
if (closed) {
return;
}
closed = true;
if (bytesRemaining > 0) {
throw new ProtocolException("unexpected end of stream");
}
}
public static int readIntAttribute(XmlPullParser in, String name) throws IOException {
final String value = in.getAttributeValue(null, name);
try {
return Integer.parseInt(value);
} catch (NumberFormatException e) {
throw new ProtocolException("problem parsing " + name + "=" + value + " as int");
}
}
/**
* Given a TCompactProtocol.Types constant, convert it to its corresponding
* TType value.
*/
private byte getTType(byte type) throws ProtocolException {
int index = type & 0x0f;
if (index < typeTable.length) {
return typeTable[index];
} else {
throw new ProtocolException("don't know what type: " + index);
}
}
@Override public final OutputStream getOutputStream() throws IOException {
connect();
OutputStream out = httpEngine.getRequestBody();
if (out == null) {
throw new ProtocolException("method does not support a request body: " + method);
} else if (httpEngine.hasResponse()) {
throw new ProtocolException("cannot write request body after response has been read");
}
return out;
}
@Override public final OutputStream getOutputStream() throws IOException {
connect();
OutputStream out = httpEngine.getRequestBody();
if (out == null) {
throw new ProtocolException("method does not support a request body: " + method);
} else if (httpEngine.hasResponse()) {
throw new ProtocolException("cannot write request body after response has been read");
}
return out;
}
@Deprecated
public static long[] readFullLongArray(DataInputStream in) throws IOException {
final int size = in.readInt();
if (size < 0) throw new ProtocolException("negative array size");
final long[] values = new long[size];
for (int i = 0; i < values.length; i++) {
values[i] = in.readLong();
}
return values;
}
public void setRequestMethod( String requestMethod ){
try {
conn.setRequestMethod(requestMethod);
conn.setDoOutput(true);
} catch( ProtocolException pe ) {
pe.printStackTrace();
}
}
public void handshakeFailed(Throwable ex)
{
try
{
ByteChannel channel=null;
synchronized (this)
{
if (_channel!=null)
{
channel=_channel;
_channel=null;
_exception=ex;
}
}
if (channel!=null)
{
if (ex instanceof ProtocolException)
closeChannel(channel,WebSocketConnectionRFC6455.CLOSE_PROTOCOL,ex.getMessage());
else
closeChannel(channel,WebSocketConnectionRFC6455.CLOSE_NO_CLOSE,ex.getMessage());
}
}
finally
{
_done.countDown();
}
}
public static long readLongAttribute(XmlPullParser in, String name) throws IOException {
final String value = in.getAttributeValue(null, name);
try {
return Long.parseLong(value);
} catch (NumberFormatException e) {
throw new ProtocolException("problem parsing " + name + "=" + value + " as long");
}
}
@Override
public void handleRedirect(
DownloadConnection originalConnection,
DownloadConnection.Connected originalConnected,
Map<String, List<String>> headerProperties) throws IOException {
int responseCode = originalConnected.getResponseCode();
int redirectCount = 0;
final DownloadUrlConnection downloadUrlConnection =
(DownloadUrlConnection) originalConnection;
while (RedirectUtil.isRedirect(responseCode)) {
// the last connect is useless, so release it
downloadUrlConnection.release();
if (++redirectCount > RedirectUtil.MAX_REDIRECT_TIMES) {
throw new ProtocolException("Too many redirect requests: " + redirectCount);
}
redirectLocation = RedirectUtil
.getRedirectedUrl(originalConnected, responseCode);
downloadUrlConnection.url = new URL(redirectLocation);
downloadUrlConnection.configUrlConnection();
Util.addRequestHeaderFields(headerProperties,
downloadUrlConnection);
downloadUrlConnection.connection.connect();
responseCode = downloadUrlConnection.getResponseCode();
}
}
private boolean isRecoverable(IOException e) {
// If the problem was a CertificateException from the X509TrustManager,
// do not retry, we didn't have an abrupt server initiated exception.
boolean sslFailure =
e instanceof SSLHandshakeException && e.getCause() instanceof CertificateException;
boolean protocolFailure = e instanceof ProtocolException;
return !sslFailure && !protocolFailure;
}
@Override public final OutputStream getOutputStream() throws IOException {
connect();
OutputStream out = httpEngine.getRequestBody();
if (out == null) {
throw new ProtocolException("method does not support a request body: " + method);
} else if (httpEngine.hasResponse()) {
throw new ProtocolException("cannot write request body after response has been read");
}
return out;
}
public static float readFloatAttribute(XmlPullParser in, String name) throws IOException {
final String value = in.getAttributeValue(null, name);
try {
return Float.parseFloat(value);
} catch (NumberFormatException e) {
throw new ProtocolException("problem parsing " + name + "=" + value + " as long");
}
}
/**
*
*/
private final void copySettings () {
try {
this.setRequestMethod(this.connection.getRequestMethod());
}
catch ( ProtocolException e ) {
throw new RuntimeCIFSException("Failed to set request method", e);
}
this.headerFields = null;
for ( Entry<String, List<String>> property : this.connection.getRequestProperties().entrySet() ) {
String key = property.getKey();
StringBuffer value = new StringBuffer();
Iterator<String> values = property.getValue().iterator();
while ( values.hasNext() ) {
value.append(values.next());
if ( values.hasNext() )
value.append(", ");
}
this.setRequestProperty(key, value.toString());
}
this.setAllowUserInteraction(this.connection.getAllowUserInteraction());
this.setDoInput(this.connection.getDoInput());
this.setDoOutput(this.connection.getDoOutput());
this.setIfModifiedSince(this.connection.getIfModifiedSince());
this.setUseCaches(this.connection.getUseCaches());
this.setReadTimeout(this.connection.getReadTimeout());
this.setConnectTimeout(this.connection.getConnectTimeout());
this.setInstanceFollowRedirects(this.connection.getInstanceFollowRedirects());
}
public void handshakeFailed(Throwable ex)
{
try
{
ByteChannel channel=null;
synchronized (this)
{
if (_channel!=null)
{
channel=_channel;
_channel=null;
_exception=ex;
}
}
if (channel!=null)
{
if (ex instanceof ProtocolException)
closeChannel(channel,WebSocketConnectionRFC6455.CLOSE_PROTOCOL,ex.getMessage());
else
closeChannel(channel,WebSocketConnectionRFC6455.CLOSE_NO_CLOSE,ex.getMessage());
}
}
finally
{
_done.countDown();
}
}
@Override public synchronized void write(byte[] buffer, int offset, int count)
throws IOException {
checkNotClosed();
checkOffsetAndCount(buffer.length, offset, count);
if (limit != -1 && content.size() > limit - count) {
throw new ProtocolException("exceeded content-length limit of " + limit + " bytes");
}
content.write(buffer, offset, count);
}