java.net.ProtocolException Java Examples

The following examples show how to use java.net.ProtocolException. You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may check out the related API usage on the sidebar.
Example #1
Source File: SimpleHttpClient.java    From aceql-http with GNU Lesser General Public License v2.1 6 votes vote down vote up
/**
    * 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;
   }
 
Example #2
Source File: HttpTransport.java    From android-discourse with Apache License 2.0 6 votes vote down vote up
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();
    }
}
 
Example #3
Source File: DefaultHttpDataSource.java    From MediaSDK with Apache License 2.0 6 votes vote down vote up
/**
 * 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;
}
 
Example #4
Source File: DefaultHttpDataSource.java    From K-Sonic with MIT License 6 votes vote down vote up
/**
 * 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;
}
 
Example #5
Source File: HttpTransport.java    From phonegapbootcampsite with MIT License 6 votes vote down vote up
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();
  }
}
 
Example #6
Source File: HttpURLConnectionImpl.java    From apiman with Apache License 2.0 6 votes vote down vote up
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;
  }
}
 
Example #7
Source File: TlsTunnelBuilder.java    From jframe with Apache License 2.0 6 votes vote down vote up
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;
}
 
Example #8
Source File: HttpTransport.java    From phonegap-plugin-loading-spinner with Apache License 2.0 6 votes vote down vote up
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);
  }
}
 
Example #9
Source File: Http1Codec.java    From AndroidProjects with MIT License 6 votes vote down vote up
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);
  }
}
 
Example #10
Source File: HttpTransport.java    From CordovaYoutubeVideoPlayer with MIT License 6 votes vote down vote up
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();
  }
}
 
Example #11
Source File: RealWebSocket.java    From styT with Apache License 2.0 6 votes vote down vote up
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 + "'");
  }
}
 
Example #12
Source File: HttpURLConnectionImpl.java    From reader with MIT License 6 votes vote down vote up
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;
  }
}
 
Example #13
Source File: WebSocketClient.java    From IoTgo_Android_App with MIT License 5 votes vote down vote up
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();
    }
}
 
Example #14
Source File: HttpTransport.java    From L.TileLayer.Cordova with MIT License 5 votes vote down vote up
@Override public void write(byte[] buffer, int offset, int count) throws IOException {
  checkNotClosed();
  checkOffsetAndCount(buffer.length, offset, count);
  if (count > bytesRemaining) {
    throw new ProtocolException("expected " + bytesRemaining + " bytes but received " + count);
  }
  socketOut.write(buffer, offset, count);
  bytesRemaining -= count;
}
 
Example #15
Source File: HttpTransport.java    From reader with MIT License 5 votes vote down vote up
@Override public void close() throws IOException {
  if (closed) {
    return;
  }
  closed = true;
  if (bytesRemaining > 0) {
    throw new ProtocolException("unexpected end of stream");
  }
}
 
Example #16
Source File: NtlmHttpURLConnection.java    From jcifs with GNU Lesser General Public License v2.1 5 votes vote down vote up
/**
 * 
 */
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());
}
 
Example #17
Source File: XmlUtils.java    From MyBookshelf with GNU General Public License v3.0 5 votes vote down vote up
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");
    }
}
 
Example #18
Source File: RawHeaders.java    From cordova-amazon-fireos with Apache License 2.0 5 votes vote down vote up
/** Returns headers for a name value block containing a SPDY response. */
public static RawHeaders fromNameValueBlock(List<String> nameValueBlock) throws IOException {
  if (nameValueBlock.size() % 2 != 0) {
    throw new IllegalArgumentException("Unexpected name value block: " + nameValueBlock);
  }
  String status = null;
  String version = null;
  RawHeaders result = new RawHeaders();
  for (int i = 0; i < nameValueBlock.size(); i += 2) {
    String name = nameValueBlock.get(i);
    String values = nameValueBlock.get(i + 1);
    for (int start = 0; start < values.length(); ) {
      int end = values.indexOf('\0', start);
      if (end == -1) {
        end = values.length();
      }
      String value = values.substring(start, end);
      if (":status".equals(name)) {
        status = value;
      } else if (":version".equals(name)) {
        version = value;
      } else {
        result.namesAndValues.add(name);
        result.namesAndValues.add(value);
      }
      start = end + 1;
    }
  }
  if (status == null) throw new ProtocolException("Expected ':status' header not present");
  if (version == null) throw new ProtocolException("Expected ':version' header not present");
  result.setStatusLine(version + " " + status);
  return result;
}
 
Example #19
Source File: XmlUtils.java    From MyBookshelf with GNU General Public License v3.0 5 votes vote down vote up
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");
    }
}
 
Example #20
Source File: RetryableOutputStream.java    From wildfly-samples with MIT License 5 votes vote down vote up
@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);
}
 
Example #21
Source File: Http1Codec.java    From styT with Apache License 2.0 5 votes vote down vote up
@Override public void write(Buffer source, long byteCount) throws IOException {
  if (closed) throw new IllegalStateException("closed");
  checkOffsetAndCount(source.size(), 0, byteCount);
  if (byteCount > bytesRemaining) {
    throw new ProtocolException("expected " + bytesRemaining
        + " bytes but received " + byteCount);
  }
  sink.write(source, byteCount);
  bytesRemaining -= byteCount;
}
 
Example #22
Source File: HttpTransport.java    From crosswalk-cordova-android with Apache License 2.0 5 votes vote down vote up
@Override public void write(byte[] buffer, int offset, int count) throws IOException {
  checkNotClosed();
  checkOffsetAndCount(buffer.length, offset, count);
  if (count > bytesRemaining) {
    throw new ProtocolException("expected " + bytesRemaining + " bytes but received " + count);
  }
  socketOut.write(buffer, offset, count);
  bytesRemaining -= count;
}
 
Example #23
Source File: RawHeaders.java    From bluemix-parking-meter with MIT License 5 votes vote down vote up
/** Returns headers for a name value block containing a SPDY response. */
public static RawHeaders fromNameValueBlock(List<String> nameValueBlock) throws IOException {
  if (nameValueBlock.size() % 2 != 0) {
    throw new IllegalArgumentException("Unexpected name value block: " + nameValueBlock);
  }
  String status = null;
  String version = null;
  RawHeaders result = new RawHeaders();
  for (int i = 0; i < nameValueBlock.size(); i += 2) {
    String name = nameValueBlock.get(i);
    String values = nameValueBlock.get(i + 1);
    for (int start = 0; start < values.length(); ) {
      int end = values.indexOf('\0', start);
      if (end == -1) {
        end = values.length();
      }
      String value = values.substring(start, end);
      if (":status".equals(name)) {
        status = value;
      } else if (":version".equals(name)) {
        version = value;
      } else {
        result.namesAndValues.add(name);
        result.namesAndValues.add(value);
      }
      start = end + 1;
    }
  }
  if (status == null) throw new ProtocolException("Expected ':status' header not present");
  if (version == null) throw new ProtocolException("Expected ':version' header not present");
  result.setStatusLine(version + " " + status);
  return result;
}
 
Example #24
Source File: Http2Codec.java    From AndroidProjects with MIT License 5 votes vote down vote up
/** Returns headers for a name value block containing an HTTP/2 response. */
public static Response.Builder readHttp2HeadersList(List<Header> headerBlock) throws IOException {
  StatusLine statusLine = null;
  Headers.Builder headersBuilder = new Headers.Builder();
  for (int i = 0, size = headerBlock.size(); i < size; i++) {
    Header header = headerBlock.get(i);

    // If there were multiple header blocks they will be delimited by nulls. Discard existing
    // header blocks if the existing header block is a '100 Continue' intermediate response.
    if (header == null) {
      if (statusLine != null && statusLine.code == HTTP_CONTINUE) {
        statusLine = null;
        headersBuilder = new Headers.Builder();
      }
      continue;
    }

    ByteString name = header.name;
    String value = header.value.utf8();
    if (name.equals(RESPONSE_STATUS)) {
      statusLine = StatusLine.parse("HTTP/1.1 " + value);
    } else if (!HTTP_2_SKIPPED_RESPONSE_HEADERS.contains(name)) {
      Internal.instance.addLenient(headersBuilder, name.utf8(), value);
    }
  }
  if (statusLine == null) throw new ProtocolException("Expected ':status' header not present");

  return new Response.Builder()
      .protocol(Protocol.HTTP_2)
      .code(statusLine.code)
      .message(statusLine.message)
      .headers(headersBuilder.build());
}
 
Example #25
Source File: XmlUtils.java    From cwac-netsecurity with Apache License 2.0 5 votes vote down vote up
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");
    }
}
 
Example #26
Source File: RedirectUtil.java    From okdownload with Apache License 2.0 5 votes vote down vote up
@NonNull
public static String getRedirectedUrl(DownloadConnection.Connected connected, int responseCode)
        throws IOException {
    String url = connected.getResponseHeaderField("Location");
    if (url == null) {
        throw new ProtocolException(
                "Response code is " + responseCode + " but can't find Location field");

    }
    return url;
}
 
Example #27
Source File: HttpURLConnection.java    From openjdk-8-source with GNU General Public License v2.0 5 votes vote down vote up
public synchronized void setRequestMethod(String method)
                    throws ProtocolException {
    if (connecting) {
        throw new IllegalStateException("connect in progress");
    }
    super.setRequestMethod(method);
}
 
Example #28
Source File: AopHttpsURLConnection.java    From ArgusAPM with Apache License 2.0 5 votes vote down vote up
@Override
public void setRequestMethod(String method) throws ProtocolException {
    try {
        this.myConnection.setRequestMethod(method);
    } catch (ProtocolException localProtocolException) {
        recordException(localProtocolException);
        throw localProtocolException;
    }
}
 
Example #29
Source File: RetryableOutputStream.java    From CordovaYoutubeVideoPlayer with MIT License 5 votes vote down vote up
@Override public synchronized void close() throws IOException {
  if (closed) {
    return;
  }
  closed = true;
  if (content.size() < limit) {
    throw new ProtocolException(
        "content-length promised " + limit + " bytes, but received " + content.size());
  }
}
 
Example #30
Source File: OneM2MHttpClient.java    From SI with BSD 2-Clause "Simplified" License 5 votes vote down vote up
public void setRequestMethod( String requestMethod ){
    try {
        conn.setRequestMethod(requestMethod);
        conn.setDoOutput(true);
    } catch( ProtocolException pe ) {
       pe.printStackTrace();
    }
}