类java.net.ProtocolException源码实例Demo

下面列出了怎么用java.net.ProtocolException的API类实例代码及写法,或者点击链接到github查看源代码。

源代码1 项目: MediaSDK   文件: DefaultHttpDataSource.java
/**
 * 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;
}
 
源代码2 项目: aceql-http   文件: SimpleHttpClient.java
/**
    * 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;
   }
 
源代码3 项目: android-discourse   文件: HttpTransport.java
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();
    }
}
 
源代码4 项目: jframe   文件: TlsTunnelBuilder.java
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;
}
 
源代码5 项目: K-Sonic   文件: DefaultHttpDataSource.java
/**
 * 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;
}
 
源代码6 项目: CordovaYoutubeVideoPlayer   文件: HttpTransport.java
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();
  }
}
 
源代码7 项目: reader   文件: HttpURLConnectionImpl.java
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;
  }
}
 
源代码8 项目: apiman   文件: HttpURLConnectionImpl.java
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;
  }
}
 
源代码9 项目: AndroidProjects   文件: Http1Codec.java
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);
  }
}
 
源代码11 项目: phonegapbootcampsite   文件: HttpTransport.java
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();
  }
}
 
源代码12 项目: styT   文件: RealWebSocket.java
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 + "'");
  }
}
 
源代码13 项目: android-discourse   文件: HttpTransport.java
@Override
public void close() throws IOException {
    if (closed) {
        return;
    }
    closed = true;
    if (bytesRemaining > 0) {
        throw new ProtocolException("unexpected end of stream");
    }
}
 
源代码14 项目: SI   文件: HttpOneM2MClient.java
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());
    }
}
 
源代码15 项目: IoTgo_Android_App   文件: HttpTransport.java
@Override public void close() throws IOException {
  if (closed) {
    return;
  }
  closed = true;
  if (bytesRemaining > 0) {
    throw new ProtocolException("unexpected end of stream");
  }
}
 
源代码16 项目: a   文件: XmlUtils.java
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");
    }
}
 
源代码17 项目: nettythrift   文件: TCompactProtocol.java
/**
 * 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;
}
 
源代码19 项目: IoTgo_Android_App   文件: HttpURLConnectionImpl.java
@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;
}
 
源代码20 项目: android_9.0.0_r45   文件: NetworkStatsHistory.java
@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;
}
 
源代码21 项目: SI   文件: GenericHttpClient.java
public void setRequestMethod( String requestMethod ){
    try {
        conn.setRequestMethod(requestMethod);
        conn.setDoOutput(true);
    } catch( ProtocolException pe ) {
       pe.printStackTrace();
    }
}
 
源代码22 项目: IoTgo_Android_App   文件: WebSocketClient.java
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();
    }
}
 
源代码23 项目: WeexOne   文件: XmlUtils.java
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");
    }
}
 
源代码24 项目: okdownload   文件: DownloadUrlConnection.java
@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;
}
 
源代码27 项目: MyBookshelf   文件: XmlUtils.java
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");
    }
}
 
源代码28 项目: jcifs   文件: NtlmHttpURLConnection.java
/**
 * 
 */
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());
}
 
源代码29 项目: IoTgo_Android_App   文件: WebSocketClient.java
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();
    }
}
 
源代码30 项目: wildfly-samples   文件: RetryableOutputStream.java
@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);
}
 
 类所在包
 类方法
 同包方法