List of usage examples for org.apache.http.util CharArrayBuffer CharArrayBuffer
public CharArrayBuffer(int i)
From source file:com.mcxiaoke.next.http.entity.BasicHeaderValueFormatter.java
public CharArrayBuffer formatNameValuePair(final CharArrayBuffer charBuffer, final NameValuePair nvp, final boolean quote) { AssertUtils.notNull(nvp, "Name / value pair"); final int len = estimateNameValuePairLen(nvp); CharArrayBuffer buffer = charBuffer; if (buffer == null) { buffer = new CharArrayBuffer(len); } else {//from www .j ava 2s. c o m buffer.ensureCapacity(len); } buffer.append(nvp.getName()); final String value = nvp.getValue(); if (value != null) { buffer.append('='); doFormatValue(buffer, value, quote); } return buffer; }
From source file:com.nominanuda.web.http.HttpCoreHelper.java
private CharArrayBuffer readLine(InputStream is) throws IOException { CharArrayBuffer cab = new CharArrayBuffer(128); int status = 0;//0 reading, 1 CR seen while (true) { char c = (char) is.read(); switch (c) { case (char) -1: throw new IOException("premature end of stream"); case CR://from ww w .j a v a 2 s . com if (status == 1) { cab.append(c); } status = 1; break; case LF: if (status == 1) { return cab; } else { cab.append(LF); } break; default: cab.append(c); break; } } }
From source file:com.mcxiaoke.next.http.util.URLUtils.java
/** * Returns a list of {@link org.apache.http.NameValuePair NameValuePairs} as parsed from the given string using the given character * encoding./* w w w .j av a 2 s. c o m*/ * * @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 org.apache.http.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 BasicHeaderValueParser parser = BasicHeaderValueParser.DEFAULT; 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; }
From source file:org.vietspider.net.apache.AbstractSessionInputBuffer.java
public String readLine() throws IOException { CharArrayBuffer charbuffer = new CharArrayBuffer(64); int l = readLine(charbuffer); return (l != -1) ? charbuffer.toString() : null; }
From source file:org.mycard.net.network.AndroidHttpClientConnection.java
/*** * Parses the response headers and adds them to the * given {@code headers} object, and returns the response StatusLine * @param headers store parsed header to headers. * @throws IOException/* ww w. ja va2 s . co m*/ * @return StatusLine * @see HttpClientConnection#receiveResponseHeader() */ public StatusLine parseResponseHeader(Headers headers) throws IOException, ParseException { assertOpen(); CharArrayBuffer current = new CharArrayBuffer(64); if (inbuffer.readLine(current) == -1) { throw new NoHttpResponseException("The target server failed to respond"); } // Create the status line from the status string StatusLine statusline = BasicLineParser.DEFAULT.parseStatusLine(current, new ParserCursor(0, current.length())); //if (HttpLog.LOGV) HttpLog.v("read: " + statusline); int statusCode = statusline.getStatusCode(); // Parse header body CharArrayBuffer previous = null; int headerNumber = 0; while (true) { if (current == null) { current = new CharArrayBuffer(64); } else { // This must be he buffer used to parse the status current.clear(); } int l = inbuffer.readLine(current); if (l == -1 || current.length() < 1) { break; } // Parse the header name and value // Check for folded headers first // Detect LWS-char see HTTP/1.0 or HTTP/1.1 Section 2.2 // discussion on folded headers char first = current.charAt(0); if ((first == ' ' || first == '\t') && previous != null) { // we have continuation folded header // so append value int start = 0; int length = current.length(); while (start < length) { char ch = current.charAt(start); if (ch != ' ' && ch != '\t') { break; } start++; } if (maxLineLength > 0 && previous.length() + 1 + current.length() - start > maxLineLength) { throw new IOException("Maximum line length limit exceeded"); } previous.append(' '); previous.append(current, start, current.length() - start); } else { if (previous != null) { headers.parseHeader(previous); } headerNumber++; previous = current; current = null; } if (maxHeaderCount > 0 && headerNumber >= maxHeaderCount) { throw new IOException("Maximum header count exceeded"); } } if (previous != null) { headers.parseHeader(previous); } if (statusCode >= 200) { this.metrics.incrementResponseCount(); } return statusline; }
From source file:com.mcxiaoke.next.http.entity.ContentType.java
/** * Generates textual representation of this content type which can be used as the value * of a <code>Content-Type</code> header. *//* w w w . j a v a2s . c o m*/ @Override public String toString() { final CharArrayBuffer buf = new CharArrayBuffer(64); buf.append(this.mimeType); if (this.params != null) { buf.append("; "); BasicHeaderValueFormatter.INSTANCE.formatParameters(buf, this.params, false); } else if (this.charset != null) { buf.append("; charset="); buf.append(this.charset.name()); } return buf.toString(); }
From source file:com.mirth.connect.connectors.http.HttpMessageConverter.java
/** * This method takes in a ContentType and returns an equivalent ContentType, only overriding the * charset. This is needed because ContentType.withCharset(charset) does not correctly handle * headers with multiple parameters. Parsing a ContentType from a String works, calling * toString() to get the correct header value works, but there's no way from ContentType itself * to update a specific parameter in-place. *//* www .j av a2 s . c om*/ public static ContentType setCharset(ContentType contentType, Charset charset) throws ParseException, UnsupportedCharsetException { // Get the correct header value String contentTypeString = contentType.toString(); // Parse the header manually the same way ContentType does it CharArrayBuffer buffer = new CharArrayBuffer(contentTypeString.length()); buffer.append(contentTypeString); ParserCursor cursor = new ParserCursor(0, contentTypeString.length()); HeaderElement[] elements = BasicHeaderValueParser.INSTANCE.parseElements(buffer, cursor); if (ArrayUtils.isNotEmpty(elements)) { String mimeType = elements[0].getName(); NameValuePair[] params = elements[0].getParameters(); List<NameValuePair> paramsList = new ArrayList<NameValuePair>(); boolean charsetFound = false; // Iterate through each parameter and override the charset if present if (ArrayUtils.isNotEmpty(params)) { for (NameValuePair nvp : params) { if (nvp.getName().equalsIgnoreCase("charset")) { charsetFound = true; nvp = new BasicNameValuePair(nvp.getName(), charset.name()); } paramsList.add(nvp); } } // Add the charset at the end if it wasn't found before if (!charsetFound) { paramsList.add(new BasicNameValuePair("charset", charset.name())); } // Format the header the same way ContentType does it CharArrayBuffer newBuffer = new CharArrayBuffer(64); newBuffer.append(mimeType); newBuffer.append("; "); BasicHeaderValueFormatter.INSTANCE.formatParameters(newBuffer, paramsList.toArray(new NameValuePair[paramsList.size()]), false); // Once we have the correct string, let ContentType do the rest return ContentType.parse(newBuffer.toString()); } else { throw new ParseException("Invalid content type: " + contentTypeString); } }
From source file:com.grendelscan.commons.http.apache_overrides.serializable.SerializableBasicCookie.java
@Override public String toString() { CharArrayBuffer buffer = new CharArrayBuffer(64); buffer.append("[version: "); buffer.append(Integer.toString(cookieVersion)); buffer.append("]"); buffer.append("[name: "); buffer.append(name);// w ww. ja v a2s .co m buffer.append("]"); buffer.append("[name: "); buffer.append(value); buffer.append("]"); buffer.append("[domain: "); buffer.append(cookieDomain); buffer.append("]"); buffer.append("[path: "); buffer.append(cookiePath); buffer.append("]"); buffer.append("[expiry: "); buffer.append(cookieExpiryDate); buffer.append("]"); return buffer.toString(); }
From source file:org.odk.collect.android.utilities.EnhancedDigestScheme.java
/** * Creates digest-response header as defined in RFC2617. * /*from www. jav a2s . c o m*/ * @param credentials * User credentials * * @return The digest-response as String. */ private Header createDigestHeader(final Credentials credentials) throws AuthenticationException { String uri = getParameter("uri"); String realm = getParameter("realm"); String nonce = getParameter("nonce"); String opaque = getParameter("opaque"); String method = getParameter("methodname"); String algorithm = getParameter("algorithm"); if (uri == null) { throw new IllegalStateException("URI may not be null"); } if (realm == null) { throw new IllegalStateException("Realm may not be null"); } if (nonce == null) { throw new IllegalStateException("Nonce may not be null"); } // TODO: add support for QOP_INT int qop = QOP_UNKNOWN; String qoplist = getParameter("qop"); if (qoplist != null) { StringTokenizer tok = new StringTokenizer(qoplist, ","); while (tok.hasMoreTokens()) { String variant = tok.nextToken().trim(); if (variant.equals("auth")) { qop = QOP_AUTH; break; } } } else { qop = QOP_MISSING; } if (qop == QOP_UNKNOWN) { throw new AuthenticationException("None of the qop methods is supported: " + qoplist); } // If an algorithm is not specified, default to MD5. if (algorithm == null) { algorithm = "MD5"; } // If an charset is not specified, default to ISO-8859-1. String charset = getParameter("charset"); if (charset == null) { charset = "ISO-8859-1"; } String digAlg = algorithm; if (digAlg.equalsIgnoreCase("MD5-sess")) { digAlg = "MD5"; } MessageDigest digester; try { digester = createMessageDigest(digAlg); } catch (UnsupportedDigestAlgorithmException ex) { throw new AuthenticationException("Unsuppported digest algorithm: " + digAlg); } String uname = credentials.getUserPrincipal().getName(); String pwd = credentials.getPassword(); if (nonce.equals(this.lastNonce)) { nounceCount++; } else { nounceCount = 1; cnonce = null; lastNonce = nonce; } StringBuilder sb = new StringBuilder(256); Formatter formatter = new Formatter(sb, Locale.US); formatter.format("%08x", nounceCount); String nc = sb.toString(); if (cnonce == null) { cnonce = createCnonce(); } a1 = null; a2 = null; // 3.2.2.2: Calculating digest if (algorithm.equalsIgnoreCase("MD5-sess")) { // H( unq(username-value) ":" unq(realm-value) ":" passwd ) // ":" unq(nonce-value) // ":" unq(cnonce-value) // calculated one per session sb.setLength(0); sb.append(uname).append(':').append(realm).append(':').append(pwd); String checksum = encode(digester.digest(EncodingUtils.getBytes(sb.toString(), charset))); sb.setLength(0); sb.append(checksum).append(':').append(nonce).append(':').append(cnonce); a1 = sb.toString(); } else { // unq(username-value) ":" unq(realm-value) ":" passwd sb.setLength(0); sb.append(uname).append(':').append(realm).append(':').append(pwd); a1 = sb.toString(); } String hasha1 = encode(digester.digest(EncodingUtils.getBytes(a1, charset))); if (qop == QOP_AUTH) { // Method ":" digest-uri-value a2 = method + ':' + uri; } else if (qop == QOP_AUTH_INT) { // Method ":" digest-uri-value ":" H(entity-body) // TODO: calculate entity hash if entity is repeatable throw new AuthenticationException("qop-int method is not suppported"); } else { a2 = method + ':' + uri; } String hasha2 = encode(digester.digest(EncodingUtils.getBytes(a2, charset))); // 3.2.2.1 String digestValue; if (qop == QOP_MISSING) { sb.setLength(0); sb.append(hasha1).append(':').append(nonce).append(':').append(hasha2); digestValue = sb.toString(); } else { sb.setLength(0); sb.append(hasha1).append(':').append(nonce).append(':').append(nc).append(':').append(cnonce) .append(':').append(qop == QOP_AUTH_INT ? "auth-int" : "auth").append(':').append(hasha2); digestValue = sb.toString(); } String digest = encode(digester.digest(EncodingUtils.getAsciiBytes(digestValue))); CharArrayBuffer buffer = new CharArrayBuffer(128); if (isProxy()) { buffer.append(AUTH.PROXY_AUTH_RESP); } else { buffer.append(AUTH.WWW_AUTH_RESP); } buffer.append(": Digest "); List<BasicNameValuePair> params = new ArrayList<BasicNameValuePair>(20); params.add(new BasicNameValuePair("username", uname)); params.add(new BasicNameValuePair("realm", realm)); params.add(new BasicNameValuePair("nonce", nonce)); params.add(new BasicNameValuePair("uri", uri)); params.add(new BasicNameValuePair("response", digest)); if (qop != QOP_MISSING) { params.add(new BasicNameValuePair("qop", qop == QOP_AUTH_INT ? "auth-int" : "auth")); params.add(new BasicNameValuePair("nc", nc)); params.add(new BasicNameValuePair("cnonce", cnonce)); } if (algorithm != null) { params.add(new BasicNameValuePair("algorithm", algorithm)); } if (opaque != null) { params.add(new BasicNameValuePair("opaque", opaque)); } for (int i = 0; i < params.size(); i++) { BasicNameValuePair param = params.get(i); if (i > 0) { buffer.append(", "); } boolean noQuotes = "nc".equals(param.getName()) || "qop".equals(param.getName()); BasicHeaderValueFormatter.DEFAULT.formatNameValuePair(buffer, param, !noQuotes); } return new BufferedHeader(buffer); }
From source file:im.delight.android.webrequest.WebRequest.java
protected String parseResponse(HttpResponse response) throws Exception { final Header contentEncoding = response.getFirstHeader("Content-Encoding"); // if we have a compressed response (GZIP) if (contentEncoding != null && contentEncoding.getValue() != null && contentEncoding.getValue().equalsIgnoreCase("gzip")) { // get the entity and the content length (if any) from the response final HttpEntity entity = response.getEntity(); long contentLength = entity.getContentLength(); // handle too large or undefined content lengths if (contentLength > Integer.MAX_VALUE) { throw new Exception("Response too large"); } else if (contentLength < 0) { // use an arbitrary buffer size contentLength = 4096;// w w w . j av a2 s.c o m } // construct a GZIP input stream from the response InputStream responseStream = entity.getContent(); if (responseStream == null) { return null; } responseStream = new GZIPInputStream(responseStream); // read from the stream Reader reader = new InputStreamReader(responseStream, mCharset); CharArrayBuffer buffer = new CharArrayBuffer((int) contentLength); try { char[] tmp = new char[1024]; int l; while ((l = reader.read(tmp)) != -1) { buffer.append(tmp, 0, l); } } finally { reader.close(); } // return the decompressed response text as a string return buffer.toString(); } // if we have an uncompressed response else { // return the response text as a string return EntityUtils.toString(response.getEntity(), mCharset); } }