Java 类org.apache.commons.httpclient.util.EncodingUtil 实例源码

项目:lib-commons-httpclient    文件:PostMethod.java   
/**
 * Generates a request entity from the post parameters, if present.  Calls
 * {@link EntityEnclosingMethod#generateRequestBody()} if parameters have not been set.
 * 
 * @since 3.0
 */
protected RequestEntity generateRequestEntity() {
    if (!this.params.isEmpty()) {
        // Use a ByteArrayRequestEntity instead of a StringRequestEntity.
        // This is to avoid potential encoding issues.  Form url encoded strings
        // are ASCII by definition but the content type may not be.  Treating the content
        // as bytes allows us to keep the current charset without worrying about how
        // this charset will effect the encoding of the form url encoded string.
        String content = EncodingUtil.formUrlEncode(getParameters(), getRequestCharSet());
        ByteArrayRequestEntity entity = new ByteArrayRequestEntity(
            EncodingUtil.getAsciiBytes(content),
            FORM_URL_ENCODED_CONTENT_TYPE
        );
        return entity;
    } else {
        return super.generateRequestEntity();
    }
}
项目:lib-commons-httpclient    文件:DigestScheme.java   
/**
 * Creates a random cnonce value based on the current time.
 * 
 * @return The cnonce value as String.
 * @throws HttpClientError if MD5 algorithm is not supported.
 */
public static String createCnonce() {
    LOG.trace("enter DigestScheme.createCnonce()");

    String cnonce;
    final String digAlg = "MD5";
    MessageDigest md5Helper;

    try {
        md5Helper = MessageDigest.getInstance(digAlg);
    } catch (NoSuchAlgorithmException e) {
        throw new HttpClientError(
          "Unsupported algorithm in HTTP Digest authentication: "
           + digAlg);
    }

    cnonce = Long.toString(System.currentTimeMillis());
    cnonce = encode(md5Helper.digest(EncodingUtil.getAsciiBytes(cnonce)));

    return cnonce;
}
项目:lib-commons-httpclient    文件:BasicScheme.java   
/**
 * Returns a basic <tt>Authorization</tt> header value for the given 
 * {@link UsernamePasswordCredentials} and charset.
 * 
 * @param credentials The credentials to encode.
 * @param charset The charset to use for encoding the credentials
 * 
 * @return a basic authorization string
 * 
 * @since 3.0
 */
public static String authenticate(UsernamePasswordCredentials credentials, String charset) {

    LOG.trace("enter BasicScheme.authenticate(UsernamePasswordCredentials, String)");

    if (credentials == null) {
        throw new IllegalArgumentException("Credentials may not be null"); 
    }
    if (charset == null || charset.length() == 0) {
        throw new IllegalArgumentException("charset may not be null or empty");
    }
    StringBuffer buffer = new StringBuffer();
    buffer.append(credentials.getUserName());
    buffer.append(":");
    buffer.append(credentials.getPassword());

    return "Basic " + EncodingUtil.getAsciiString(
            Base64.encodeBase64(EncodingUtil.getBytes(buffer.toString(), charset)));
}
项目:lib-commons-httpclient    文件:TestStreams.java   
public void testCorruptChunkedInputStream1() throws IOException {
    //missing \r\n at the end of the first chunk
    String corrupInput = "10;key=\"value\"\r\n123456789012345\r\n5\r\n12345\r\n0\r\nFooter1: abcde\r\nFooter2: fghij\r\n";
    HttpMethod method = new FakeHttpMethod();

    InputStream in = new ChunkedInputStream(new ByteArrayInputStream(
        EncodingUtil.getBytes(corrupInput, CONTENT_CHARSET)), method);
    byte[] buffer = new byte[300];
    ByteArrayOutputStream out = new ByteArrayOutputStream();
    int len;
    try {
        while ((len = in.read(buffer)) > 0) {
            out.write(buffer, 0, len);
        }
        fail("Should have thrown exception");
    } catch(IOException e) {
        /* expected exception */
    }
}
项目:lib-commons-httpclient    文件:TestStreams.java   
public void testChunkedConsitance() throws IOException {
    String input = "76126;27823abcd;:q38a-\nkjc\rk%1ad\tkh/asdui\r\njkh+?\\suweb";
    ByteArrayOutputStream buffer = new ByteArrayOutputStream();
    OutputStream out = new ChunkedOutputStream(buffer);
    out.write(EncodingUtil.getBytes(input, CONTENT_CHARSET));
    out.close();
    buffer.close();
    InputStream in = new ChunkedInputStream(new ByteArrayInputStream(buffer.toByteArray()), new GetMethod());

    byte[] d = new byte[10];
    ByteArrayOutputStream result = new ByteArrayOutputStream();
    int len = 0;
    while ((len = in.read(d)) > 0) {
        result.write(d, 0, len);
    }

    String output = EncodingUtil.getString(result.toByteArray(), CONTENT_CHARSET);
    assertEquals(input, output);
}
项目:lib-commons-httpclient    文件:TestBasicAuth.java   
public void testCustomAuthorizationHeader() throws Exception {
    UsernamePasswordCredentials creds = 
        new UsernamePasswordCredentials("testuser", "testpass");

    HttpRequestHandlerChain handlerchain = new HttpRequestHandlerChain();
    handlerchain.appendHandler(new AuthRequestHandler(creds));
    handlerchain.appendHandler(new HttpServiceHandler(new FeedbackService()));

    this.server.setRequestHandler(handlerchain);

    GetMethod httpget = new GetMethod("/test/");
    String authResponse = "Basic " + EncodingUtil.getAsciiString(
            Base64.encodeBase64(EncodingUtil.getAsciiBytes("testuser:testpass")));
    httpget.addRequestHeader(new Header("Authorization", authResponse));
    try {
        this.client.executeMethod(httpget);
    } finally {
        httpget.releaseConnection();
    }
    assertNotNull(httpget.getStatusLine());
    assertEquals(HttpStatus.SC_OK, httpget.getStatusLine().getStatusCode());
}
项目:Lucee4    文件:ResourcePart.java   
public static void sendDispositionHeader(String name,String filename, String headerCharset, OutputStream out)  throws IOException {
    out.write(CONTENT_DISPOSITION_BYTES);
    out.write(QUOTE_BYTES);
    if(StringUtil.isAscii(name))
        out.write(EncodingUtil.getAsciiBytes(name));
    else
        out.write(name.getBytes(headerCharset));
    out.write(QUOTE_BYTES);

    if (filename != null) {
        out.write(FILE_NAME_BYTES);
        out.write(QUOTE_BYTES);
        if(StringUtil.isAscii(filename))
            out.write(EncodingUtil.getAsciiBytes(filename));
        else
            out.write(filename.getBytes(headerCharset));
        out.write(QUOTE_BYTES);
    }
}
项目:webarchive-commons    文件:LaxHttpParser.java   
/**
 * Read up to <tt>"\n"</tt> from an (unchunked) input stream.
 * If the stream ends before the line terminator is found,
 * the last part of the string will still be returned.
 * If no input data available, <code>null</code> is returned.
 *
 * @param inputStream the stream to read from
 * @param charset charset of HTTP protocol elements
 *
 * @throws IOException if an I/O problem occurs
 * @return a line from the stream
 * 
 * @since 3.0
 */
public static String readLine(InputStream inputStream, String charset) throws IOException {
    LOG.trace("enter LaxHttpParser.readLine(InputStream, String)");
    byte[] rawdata = readRawLine(inputStream);
    if (rawdata == null) {
        return null;
    }
    // strip CR and LF from the end
    int len = rawdata.length;
    int offset = 0;
    if (len > 0) {
        if (rawdata[len - 1] == '\n') {
            offset++;
            if (len > 1) {
                if (rawdata[len - 2] == '\r') {
                    offset++;
                }
            }
        }
    }
    return EncodingUtil.getString(rawdata, 0, len - offset, charset);
}
项目:httpclient3-ntml    文件:HttpParser.java   
/**
 * Read up to <tt>"\n"</tt> from an (unchunked) input stream.
 * If the stream ends before the line terminator is found,
 * the last part of the string will still be returned.
 * If no input data available, <code>null</code> is returned.
 *
 * @param inputStream the stream to read from
 * @param charset charset of HTTP protocol elements
 *
 * @throws IOException if an I/O problem occurs
 * @return a line from the stream
 * 
 * @since 3.0
 */
public static String readLine(InputStream inputStream, String charset) throws IOException {
    LOG.trace("enter HttpParser.readLine(InputStream, String)");
    byte[] rawdata = readRawLine(inputStream);
    if (rawdata == null) {
        return null;
    }
    // strip CR and LF from the end
    int len = rawdata.length;
    int offset = 0;
    if (len > 0) {
        if (rawdata[len - 1] == '\n') {
            offset++;
            if (len > 1) {
                if (rawdata[len - 2] == '\r') {
                    offset++;
                }
            }
        }
    }
    return EncodingUtil.getString(rawdata, 0, len - offset, charset);
}
项目:httpclient3-ntml    文件:PostMethod.java   
/**
 * Generates a request entity from the post parameters, if present.  Calls
 * {@link EntityEnclosingMethod#generateRequestBody()} if parameters have not been set.
 * 
 * @since 3.0
 */
protected RequestEntity generateRequestEntity() {
    if (!this.params.isEmpty()) {
        // Use a ByteArrayRequestEntity instead of a StringRequestEntity.
        // This is to avoid potential encoding issues.  Form url encoded strings
        // are ASCII by definition but the content type may not be.  Treating the content
        // as bytes allows us to keep the current charset without worrying about how
        // this charset will effect the encoding of the form url encoded string.
        String content = EncodingUtil.formUrlEncode(getParameters(), getRequestCharSet());
        ByteArrayRequestEntity entity = new ByteArrayRequestEntity(
            EncodingUtil.getAsciiBytes(content),
            FORM_URL_ENCODED_CONTENT_TYPE
        );
        return entity;
    } else {
        return super.generateRequestEntity();
    }
}
项目:httpclient3-ntml    文件:DigestScheme.java   
/**
 * Creates a random cnonce value based on the current time.
 * 
 * @return The cnonce value as String.
 * @throws HttpClientError if MD5 algorithm is not supported.
 */
public static String createCnonce() {
    LOG.trace("enter DigestScheme.createCnonce()");

    String cnonce;
    final String digAlg = "MD5";
    MessageDigest md5Helper;

    try {
        md5Helper = MessageDigest.getInstance(digAlg);
    } catch (NoSuchAlgorithmException e) {
        throw new HttpClientError(
          "Unsupported algorithm in HTTP Digest authentication: "
           + digAlg);
    }

    cnonce = Long.toString(System.currentTimeMillis());
    cnonce = encode(md5Helper.digest(EncodingUtil.getAsciiBytes(cnonce)));

    return cnonce;
}
项目:httpclient3-ntml    文件:BasicScheme.java   
/**
 * Returns a basic <tt>Authorization</tt> header value for the given 
 * {@link UsernamePasswordCredentials} and charset.
 * 
 * @param credentials The credentials to encode.
 * @param charset The charset to use for encoding the credentials
 * 
 * @return a basic authorization string
 * 
 * @since 3.0
 */
public static String authenticate(UsernamePasswordCredentials credentials, String charset) {

    LOG.trace("enter BasicScheme.authenticate(UsernamePasswordCredentials, String)");

    if (credentials == null) {
        throw new IllegalArgumentException("Credentials may not be null"); 
    }
    if (charset == null || charset.length() == 0) {
        throw new IllegalArgumentException("charset may not be null or empty");
    }
    StringBuffer buffer = new StringBuffer();
    buffer.append(credentials.getUserName());
    buffer.append(":");
    buffer.append(credentials.getPassword());

    return "Basic " + EncodingUtil.getAsciiString(
            Base64.encodeBase64(EncodingUtil.getBytes(buffer.toString(), charset)));
}
项目:httpclient3-ntml    文件:TestStreams.java   
public void testCorruptChunkedInputStream1() throws IOException {
    //missing \r\n at the end of the first chunk
    String corrupInput = "10;key=\"value\"\r\n123456789012345\r\n5\r\n12345\r\n0\r\nFooter1: abcde\r\nFooter2: fghij\r\n";
    HttpMethod method = new FakeHttpMethod();

    InputStream in = new ChunkedInputStream(new ByteArrayInputStream(
        EncodingUtil.getBytes(corrupInput, CONTENT_CHARSET)), method);
    byte[] buffer = new byte[300];
    ByteArrayOutputStream out = new ByteArrayOutputStream();
    int len;
    try {
        while ((len = in.read(buffer)) > 0) {
            out.write(buffer, 0, len);
        }
        fail("Should have thrown exception");
    } catch(IOException e) {
        /* expected exception */
    }
}
项目:httpclient3-ntml    文件:TestStreams.java   
public void testChunkedConsitance() throws IOException {
    String input = "76126;27823abcd;:q38a-\nkjc\rk%1ad\tkh/asdui\r\njkh+?\\suweb";
    ByteArrayOutputStream buffer = new ByteArrayOutputStream();
    OutputStream out = new ChunkedOutputStream(buffer);
    out.write(EncodingUtil.getBytes(input, CONTENT_CHARSET));
    out.close();
    buffer.close();
    InputStream in = new ChunkedInputStream(new ByteArrayInputStream(buffer.toByteArray()), new GetMethod());

    byte[] d = new byte[10];
    ByteArrayOutputStream result = new ByteArrayOutputStream();
    int len = 0;
    while ((len = in.read(d)) > 0) {
        result.write(d, 0, len);
    }

    String output = EncodingUtil.getString(result.toByteArray(), CONTENT_CHARSET);
    assertEquals(input, output);
}
项目:httpclient3-ntml    文件:TestBasicAuth.java   
public void testCustomAuthorizationHeader() throws Exception {
    UsernamePasswordCredentials creds = 
        new UsernamePasswordCredentials("testuser", "testpass");

    HttpRequestHandlerChain handlerchain = new HttpRequestHandlerChain();
    handlerchain.appendHandler(new AuthRequestHandler(creds));
    handlerchain.appendHandler(new HttpServiceHandler(new FeedbackService()));

    this.server.setRequestHandler(handlerchain);

    GetMethod httpget = new GetMethod("/test/");
    String authResponse = "Basic " + EncodingUtil.getAsciiString(
            Base64.encodeBase64(EncodingUtil.getAsciiBytes("testuser:testpass")));
    httpget.addRequestHeader(new Header("Authorization", authResponse));
    try {
        this.client.executeMethod(httpget);
    } finally {
        httpget.releaseConnection();
    }
    assertNotNull(httpget.getStatusLine());
    assertEquals(HttpStatus.SC_OK, httpget.getStatusLine().getStatusCode());
}
项目:alfresco-repository    文件:ContentDataPart.java   
/**
 * Write the disposition header to the output stream
 * @param out The output stream
 * @throws IOException If an IO problem occurs
 * @see org.apache.commons.httpclient.methods.multipart.Part#sendDispositionHeader(OutputStream)
 */
protected void sendDispositionHeader(OutputStream out) 
throws IOException {
    super.sendDispositionHeader(out);
    if (filename != null) {
        out.write(FILE_NAME_BYTES);
        out.write(QUOTE_BYTES);
        out.write(EncodingUtil.getAsciiBytes(filename));
        out.write(QUOTE_BYTES);
    }
}
项目:alfresco-remote-api    文件:HttpResponse.java   
public String getResponse()
{
    if (responseBytes != null)
    {
        if (method instanceof HttpMethodBase)
        {
            // mimic method.getResponseBodyAsString
            return EncodingUtil.getString(responseBytes, ((HttpMethodBase)method).getResponseCharSet());
        }
        else
        {
            return new String(responseBytes);
        }
    }
    else
    {
        return null;
    }
}
项目:lib-commons-httpclient    文件:HttpParser.java   
/**
 * Read up to <tt>"\n"</tt> from an (unchunked) input stream.
 * If the stream ends before the line terminator is found,
 * the last part of the string will still be returned.
 * If no input data available, <code>null</code> is returned.
 *
 * @param inputStream the stream to read from
 * @param charset charset of HTTP protocol elements
 *
 * @throws IOException if an I/O problem occurs
 * @return a line from the stream
 * 
 * @since 3.0
 */
public static String readLine(InputStream inputStream, String charset) throws IOException {
    LOG.trace("enter HttpParser.readLine(InputStream, String)");
    byte[] rawdata = readRawLine(inputStream);
    if (rawdata == null) {
        return null;
    }
    // strip CR and LF from the end
    int len = rawdata.length;
    int offset = 0;
    if (len > 0) {
        if (rawdata[len - 1] == '\n') {
            offset++;
            if (len > 1) {
                if (rawdata[len - 2] == '\r') {
                    offset++;
                }
            }
        }
    }
    final String result =
        EncodingUtil.getString(rawdata, 0, len - offset, charset);
    if (Wire.HEADER_WIRE.enabled()) {
        String logoutput = result;
        if (offset == 2)
            logoutput = result + "\r\n";
        else if (offset == 1)
            logoutput = result + "\n";
        Wire.HEADER_WIRE.input(logoutput);
    }
    return result;
}
项目:lib-commons-httpclient    文件:MultipartRequestEntity.java   
/**
 * Returns the MIME boundary string that is used to demarcate boundaries of
 * this part. The first call to this method will implicitly create a new
 * boundary string. To create a boundary string first the 
 * HttpMethodParams.MULTIPART_BOUNDARY parameter is considered. Otherwise 
 * a random one is generated.
 * 
 * @return The boundary string of this entity in ASCII encoding.
 */
protected byte[] getMultipartBoundary() {
    if (multipartBoundary == null) {
        String temp = (String) params.getParameter(HttpMethodParams.MULTIPART_BOUNDARY);
        if (temp != null) {
            multipartBoundary = EncodingUtil.getAsciiBytes(temp);
        } else {
            multipartBoundary = generateMultipartBoundary();
        }
    }
    return multipartBoundary;
}
项目:lib-commons-httpclient    文件:StringPart.java   
/**
 * Gets the content in bytes.  Bytes are lazily created to allow the charset to be changed
 * after the part is created.
 * 
 * @return the content in bytes
 */
private byte[] getContent() {
    if (content == null) {
        content = EncodingUtil.getBytes(value, getCharSet());
    }
    return content;
}
项目:lib-commons-httpclient    文件:Part.java   
/**
 * Write the content disposition header to the specified output stream
 * 
 * @param out The output stream
 * @throws IOException If an IO problem occurs.
 */
protected void sendDispositionHeader(OutputStream out) throws IOException {
    LOG.trace("enter sendDispositionHeader(OutputStream out)");
    out.write(CONTENT_DISPOSITION_BYTES);
    out.write(QUOTE_BYTES);
    out.write(EncodingUtil.getAsciiBytes(getName()));
    out.write(QUOTE_BYTES);
}
项目:lib-commons-httpclient    文件:Part.java   
/**
 * Write the content type header to the specified output stream
 * @param out The output stream
 * @throws IOException If an IO problem occurs.
 */
 protected void sendContentTypeHeader(OutputStream out) throws IOException {
    LOG.trace("enter sendContentTypeHeader(OutputStream out)");
    String contentType = getContentType();
    if (contentType != null) {
        out.write(CRLF_BYTES);
        out.write(CONTENT_TYPE_BYTES);
        out.write(EncodingUtil.getAsciiBytes(contentType));
        String charSet = getCharSet();
        if (charSet != null) {
            out.write(CHARSET_BYTES);
            out.write(EncodingUtil.getAsciiBytes(charSet));
        }
    }
}
项目:lib-commons-httpclient    文件:Part.java   
/**
 * Write the content transfer encoding header to the specified 
 * output stream
 * 
 * @param out The output stream
 * @throws IOException If an IO problem occurs.
 */
 protected void sendTransferEncodingHeader(OutputStream out) throws IOException {
    LOG.trace("enter sendTransferEncodingHeader(OutputStream out)");
    String transferEncoding = getTransferEncoding();
    if (transferEncoding != null) {
        out.write(CRLF_BYTES);
        out.write(CONTENT_TRANSFER_ENCODING_BYTES);
        out.write(EncodingUtil.getAsciiBytes(transferEncoding));
    }
}
项目:lib-commons-httpclient    文件:FilePart.java   
/**
 * Write the disposition header to the output stream
 * @param out The output stream
 * @throws IOException If an IO problem occurs
 * @see Part#sendDispositionHeader(OutputStream)
 */
protected void sendDispositionHeader(OutputStream out) 
throws IOException {
    LOG.trace("enter sendDispositionHeader(OutputStream out)");
    super.sendDispositionHeader(out);
    String filename = this.source.getFileName();
    if (filename != null) {
        out.write(FILE_NAME_BYTES);
        out.write(QUOTE_BYTES);
        out.write(EncodingUtil.getAsciiBytes(filename));
        out.write(QUOTE_BYTES);
    }
}
项目:lib-commons-httpclient    文件:ChunkedOutputStream.java   
/**
 * Writes the cache out onto the underlying stream
 * @throws IOException
 * 
 * @since 3.0
 */
protected void flushCache() throws IOException {
    if (cachePosition > 0) {
        byte chunkHeader[] = EncodingUtil.getAsciiBytes(
                Integer.toHexString(cachePosition) + "\r\n");
        stream.write(chunkHeader, 0, chunkHeader.length);
        stream.write(cache, 0, cachePosition);
        stream.write(ENDCHUNK, 0, ENDCHUNK.length);
        cachePosition = 0;
    }
}
项目:lib-commons-httpclient    文件:NTLM.java   
/** 
 * Returns the response that has been generated after shrinking the array if
 * required and base64 encodes the response.
 * @return The response as above.
 */
private String getResponse() {
    byte[] resp;
    if (currentResponse.length > currentPosition) {
        byte[] tmp = new byte[currentPosition];
        for (int i = 0; i < currentPosition; i++) {
            tmp[i] = currentResponse[i];
        }
        resp = tmp;
    } else {
        resp = currentResponse;
    }
    return EncodingUtil.getAsciiString(Base64.encodeBase64(resp));
}
项目:lib-commons-httpclient    文件:NTLM.java   
/** 
 * Extracts the server nonce out of the given message type 2.
 * 
 * @param message the String containing the base64 encoded message.
 * @return an array of 8 bytes that the server sent to be used when
 * hashing the password.
 */
public byte[] parseType2Message(String message) {
    // Decode the message first.
    byte[] msg = Base64.decodeBase64(EncodingUtil.getBytes(message, DEFAULT_CHARSET));
    byte[] nonce = new byte[8];
    // The nonce is the 8 bytes starting from the byte in position 24.
    for (int i = 0; i < 8; i++) {
        nonce[i] = msg[i + 24];
    }
    return nonce;
}
项目:lib-commons-httpclient    文件:TestStreams.java   
public void testEmptyChunkedInputStream() throws IOException {
    String input = "0\r\n";
    HttpMethod method = new FakeHttpMethod();

    InputStream in = new ChunkedInputStream(new ByteArrayInputStream(
        EncodingUtil.getBytes(input, CONTENT_CHARSET)), method);
    byte[] buffer = new byte[300];
    ByteArrayOutputStream out = new ByteArrayOutputStream();
    int len;
    while ((len = in.read(buffer)) > 0) {
        out.write(buffer, 0, len);
    }
    assertEquals(0, out.size());
}
项目:lib-commons-httpclient    文件:TestStreams.java   
public void testContentLengthInputStream() throws IOException {
    String correct = "1234567890123456";
    InputStream in = new ContentLengthInputStream(new ByteArrayInputStream(
        EncodingUtil.getBytes(correct, CONTENT_CHARSET)), 10L);
    byte[] buffer = new byte[50];
    int len = in.read(buffer);
    ByteArrayOutputStream out = new ByteArrayOutputStream();
    out.write(buffer, 0, len);
    String result = EncodingUtil.getString(out.toByteArray(), CONTENT_CHARSET);
    assertEquals(result, "1234567890");
}
项目:lib-commons-httpclient    文件:TestBasicAuth.java   
public void testBasicAuthenticationWithDefaultCreds() throws Exception {
    UsernamePasswordCredentials creds = 
        new UsernamePasswordCredentials("testuser", "testpass");

    HttpRequestHandlerChain handlerchain = new HttpRequestHandlerChain();
    handlerchain.appendHandler(new AuthRequestHandler(creds));
    handlerchain.appendHandler(new HttpServiceHandler(new FeedbackService()));

    HttpState state = new HttpState();
    state.setCredentials(AuthScope.ANY, creds);
    this.client.setState(state);

    this.server.setRequestHandler(handlerchain);

    GetMethod httpget = new GetMethod("/test/");
    try {
        this.client.executeMethod(httpget);
    } finally {
        httpget.releaseConnection();
    }
    assertNotNull(httpget.getStatusLine());
    assertEquals(HttpStatus.SC_OK, httpget.getStatusLine().getStatusCode());
    Header auth = httpget.getRequestHeader("Authorization");
    assertNotNull(auth);
    String expected = "Basic " + EncodingUtil.getAsciiString(
        Base64.encodeBase64(EncodingUtil.getAsciiBytes("testuser:testpass")));
    assertEquals(expected, auth.getValue());
    AuthState authstate = httpget.getHostAuthState();
    assertNotNull(authstate.getAuthScheme());
    assertTrue(authstate.getAuthScheme() instanceof BasicScheme);
    assertEquals("test", authstate.getRealm());
}
项目:lib-commons-httpclient    文件:TestBasicAuth.java   
public void testBasicAuthentication() throws Exception {
    UsernamePasswordCredentials creds = 
        new UsernamePasswordCredentials("testuser", "testpass");

    HttpRequestHandlerChain handlerchain = new HttpRequestHandlerChain();
    handlerchain.appendHandler(new AuthRequestHandler(creds));
    handlerchain.appendHandler(new HttpServiceHandler(new FeedbackService()));

    HttpState state = new HttpState();
    AuthScope authscope = new AuthScope(
        this.server.getLocalAddress(), 
        this.server.getLocalPort(),
        "test");
    state.setCredentials(authscope, creds);
    this.client.setState(state);

    this.server.setRequestHandler(handlerchain);

    GetMethod httpget = new GetMethod("/test/");
    try {
        this.client.executeMethod(httpget);
    } finally {
        httpget.releaseConnection();
    }
    assertNotNull(httpget.getStatusLine());
    assertEquals(HttpStatus.SC_OK, httpget.getStatusLine().getStatusCode());
    Header auth = httpget.getRequestHeader("Authorization");
    assertNotNull(auth);
    String expected = "Basic " + EncodingUtil.getAsciiString(
        Base64.encodeBase64(EncodingUtil.getAsciiBytes("testuser:testpass")));
    assertEquals(expected, auth.getValue());
    AuthState authstate = httpget.getHostAuthState();
    assertNotNull(authstate.getAuthScheme());
    assertTrue(authstate.getAuthScheme() instanceof BasicScheme);
    assertEquals("test", authstate.getRealm());
}
项目:lib-commons-httpclient    文件:TestBasicAuth.java   
public void testPreemptiveAuthorizationTrueWithCreds() throws Exception {
    UsernamePasswordCredentials creds = 
        new UsernamePasswordCredentials("testuser", "testpass");

    HttpRequestHandlerChain handlerchain = new HttpRequestHandlerChain();
    handlerchain.appendHandler(new AuthRequestHandler(creds));
    handlerchain.appendHandler(new HttpServiceHandler(new FeedbackService()));

    HttpState state = new HttpState();
    state.setCredentials(AuthScope.ANY, creds);
    this.client.setState(state);
    this.client.getParams().setAuthenticationPreemptive(true);

    this.server.setRequestHandler(handlerchain);

    GetMethod httpget = new GetMethod("/test/");
    try {
        this.client.executeMethod(httpget);
    } finally {
        httpget.releaseConnection();
    }
    assertNotNull(httpget.getStatusLine());
    assertEquals(HttpStatus.SC_OK, httpget.getStatusLine().getStatusCode());
    Header auth = httpget.getRequestHeader("Authorization");
    assertNotNull(auth);
    String expected = "Basic " + EncodingUtil.getAsciiString(
        Base64.encodeBase64(EncodingUtil.getAsciiBytes("testuser:testpass")));
    assertEquals(expected, auth.getValue());
    AuthState authstate = httpget.getHostAuthState();
    assertNotNull(authstate.getAuthScheme());
    assertTrue(authstate.getAuthScheme() instanceof BasicScheme);
    assertNull(authstate.getRealm());
    assertTrue(authstate.isPreemptive());
}
项目:lib-commons-httpclient    文件:TestBasicAuth.java   
public void testHeadBasicAuthentication() throws Exception {
    UsernamePasswordCredentials creds = 
        new UsernamePasswordCredentials("testuser", "testpass");

    HttpRequestHandlerChain handlerchain = new HttpRequestHandlerChain();
    handlerchain.appendHandler(new AuthRequestHandler(creds));
    handlerchain.appendHandler(new HttpServiceHandler(new FeedbackService()));

    HttpState state = new HttpState();
    AuthScope authscope = new AuthScope(
        this.server.getLocalAddress(), 
        this.server.getLocalPort(),
        "test");
    state.setCredentials(authscope, creds);
    this.client.setState(state);

    this.server.setRequestHandler(handlerchain);

    HeadMethod head = new HeadMethod("/test/");
    try {
        this.client.executeMethod(head);
    } finally {
        head.releaseConnection();
    }
    assertNotNull(head.getStatusLine());
    assertEquals(HttpStatus.SC_OK, head.getStatusLine().getStatusCode());
    Header auth = head.getRequestHeader("Authorization");
    assertNotNull(auth);
    String expected = "Basic " + EncodingUtil.getAsciiString(
        Base64.encodeBase64(EncodingUtil.getAsciiBytes("testuser:testpass")));
    assertEquals(expected, auth.getValue());
    AuthState authstate = head.getHostAuthState();
    assertNotNull(authstate.getAuthScheme());
    assertTrue(authstate.getAuthScheme() instanceof BasicScheme);
    assertEquals("test", authstate.getRealm());
}
项目:lib-commons-httpclient    文件:TestBasicAuth.java   
public void testPostBasicAuthentication() throws Exception {
    UsernamePasswordCredentials creds = 
        new UsernamePasswordCredentials("testuser", "testpass");

    HttpRequestHandlerChain handlerchain = new HttpRequestHandlerChain();
    handlerchain.appendHandler(new AuthRequestHandler(creds));
    handlerchain.appendHandler(new HttpServiceHandler(new EchoService()));

    HttpState state = new HttpState();
    AuthScope authscope = new AuthScope(
        this.server.getLocalAddress(), 
        this.server.getLocalPort(),
        "test");
    state.setCredentials(authscope, creds);
    this.client.setState(state);

    this.server.setRequestHandler(handlerchain);

    PostMethod post = new PostMethod("/test/");
    post.setRequestEntity(new StringRequestEntity("Test body", null, null));
    try {
        this.client.executeMethod(post);
        assertEquals("Test body", post.getResponseBodyAsString());
    } finally {
        post.releaseConnection();
    }
    assertNotNull(post.getStatusLine());
    assertEquals(HttpStatus.SC_OK, post.getStatusLine().getStatusCode());
    Header auth = post.getRequestHeader("Authorization");
    assertNotNull(auth);
    String expected = "Basic " + EncodingUtil.getAsciiString(
        Base64.encodeBase64(EncodingUtil.getAsciiBytes("testuser:testpass")));
    assertEquals(expected, auth.getValue());
    AuthState authstate = post.getHostAuthState();
    assertNotNull(authstate.getAuthScheme());
    assertTrue(authstate.getAuthScheme() instanceof BasicScheme);
    assertEquals("test", authstate.getRealm());
}
项目:lib-commons-httpclient    文件:TestBasicAuth.java   
public void testPutBasicAuthentication() throws Exception {
    UsernamePasswordCredentials creds = 
        new UsernamePasswordCredentials("testuser", "testpass");

    HttpRequestHandlerChain handlerchain = new HttpRequestHandlerChain();
    handlerchain.appendHandler(new AuthRequestHandler(creds));
    handlerchain.appendHandler(new HttpServiceHandler(new EchoService()));

    HttpState state = new HttpState();
    AuthScope authscope = new AuthScope(
        this.server.getLocalAddress(), 
        this.server.getLocalPort(),
        "test");
    state.setCredentials(authscope, creds);
    this.client.setState(state);

    this.server.setRequestHandler(handlerchain);

    PutMethod put = new PutMethod("/test/");
    put.setRequestEntity(new StringRequestEntity("Test body", null, null));
    try {
        this.client.executeMethod(put);
        assertEquals("Test body", put.getResponseBodyAsString());
    } finally {
        put.releaseConnection();
    }
    assertNotNull(put.getStatusLine());
    assertEquals(HttpStatus.SC_OK, put.getStatusLine().getStatusCode());
    Header auth = put.getRequestHeader("Authorization");
    assertNotNull(auth);
    String expected = "Basic " + EncodingUtil.getAsciiString(
        Base64.encodeBase64(EncodingUtil.getAsciiBytes("testuser:testpass")));
    assertEquals(expected, auth.getValue());
    AuthState authstate = put.getHostAuthState();
    assertNotNull(authstate.getAuthScheme());
    assertTrue(authstate.getAuthScheme() instanceof BasicScheme);
    assertEquals("test", authstate.getRealm());
}
项目:javabase    文件:OldHttpClientApi.java   
public void  get2(){
    String requesturl = "http://www.tuling123.com/openapi/api";
    GetMethod getMethod = new GetMethod(requesturl);
    try {
        String APIKEY = "4b441cb500f431adc6cc0cb650b4a5d0";
        String INFO ="北京时间";

        //get  参数
        NameValuePair nvp1=new NameValuePair("key",APIKEY);
        NameValuePair nvp2=new NameValuePair("info",INFO);
        NameValuePair[] nvp = new NameValuePair[2];
        nvp[0]=nvp1;
        nvp[1]=nvp2;
        String params=EncodingUtil.formUrlEncode(nvp, "UTF-8");
        //设置参数
        getMethod.setQueryString(params);

        byte[] responseBody = executeMethod(getMethod,10000);

         String content=new String(responseBody ,"utf-8");
        log.info(content);
    }catch (Exception e){
       log.error(""+e.getLocalizedMessage());
    }finally {
        //结束一定要关闭
        getMethod.releaseConnection();
    }
}
项目:javabase    文件:HttpClientUtil.java   
/**
 * 转换成queryString
 * @param params
 *            存档参数名与参数值的集合
 * @return queryString
 */
public static String getQueryString(Map<String, String> params) {
    String queryString = null;
    if (params != null) {
        NameValuePair[] nvp = new NameValuePair[params.size()];
        int index = 0;
        for(String key : params.keySet()) {
            nvp[index++] = new NameValuePair(key, params.get(key));
        }
        queryString = EncodingUtil.formUrlEncode(nvp, "UTF-8");
    }
    return queryString == null ? "" : queryString;
}
项目:community-edition-old    文件:HttpResponse.java   
public String getResponse()
{
    if (responseBytes != null)
    {
        if (method instanceof HttpMethodBase)
        {
            // mimic method.getResponseBodyAsString
            return EncodingUtil.getString(responseBytes, ((HttpMethodBase)method).getResponseCharSet());
        }
        else
        {
            return new String(responseBytes);
        }
    }
    else
    {
        return null;
    }
}
项目:community-edition-old    文件:ContentDataPart.java   
/**
 * Write the disposition header to the output stream
 * @param out The output stream
 * @throws IOException If an IO problem occurs
 * @see org.apache.commons.httpclient.methods.multipart.Part#sendDispositionHeader(OutputStream)
 */
protected void sendDispositionHeader(OutputStream out) 
throws IOException {
    super.sendDispositionHeader(out);
    if (filename != null) {
        out.write(FILE_NAME_BYTES);
        out.write(QUOTE_BYTES);
        out.write(EncodingUtil.getAsciiBytes(filename));
        out.write(QUOTE_BYTES);
    }
}
项目:netarchivesuite-svngit-migration    文件:NetarchiveSuiteWARCRecordToSearchResultAdapter.java   
private CaptureSearchResult adaptWARCHTTPResponse(CaptureSearchResult result,
        WARCRecord rec) throws IOException {

    ArchiveRecordHeader header = rec.getHeader();
    // need to parse the documents HTTP message and headers here: WARCReader
    // does not implement this... yet..

       byte [] statusBytes = HttpParser.readRawLine(rec);
       int eolCharCount = getEolCharsCount(statusBytes);
       if (eolCharCount <= 0) {
           throw new RecoverableIOException("Failed to read http status where one " +
                   " was expected: " + 
                   ((statusBytes == null) ? "(null)" : new String(statusBytes)));
       }
       String statusLine = EncodingUtil.getString(statusBytes, 0,
           statusBytes.length - eolCharCount, ARCConstants.DEFAULT_ENCODING);
       if ((statusLine == null) ||
               !StatusLine.startsWithHTTP(statusLine)) {
          throw new RecoverableIOException("Failed parse of http status line.");
       }
       StatusLine status = new StatusLine(statusLine);
    result.setHttpCode(String.valueOf(status.getStatusCode()));

    Header[] headers = HttpParser.parseHeaders(rec,
               ARCConstants.DEFAULT_ENCODING);


    annotater.annotateHTTPContent(result,rec,headers,header.getMimetype());

    return result;
}