如何将字符串转换为Apache HttpComponents HttpRequest

时间:2012-03-26 21:26:23

标签: apache-httpcomponents

我有一个包含HTTP标头的String。我想把它变成一个Apache HttpComponents HttpRequest对象。有没有办法在不自行拆分字符串的情况下做到这一点?

本教程:http://hc.apache.org/httpcomponents-core-dev/tutorial/html/fundamentals.html#d5e56和javadoc没有表明那么多。

1 个答案:

答案 0 :(得分:13)

将字符串转换为apache请求的类:

import org.apache.http.*;
import org.apache.http.impl.DefaultHttpRequestFactory;
import org.apache.http.impl.entity.EntityDeserializer;
import org.apache.http.impl.entity.LaxContentLengthStrategy;
import org.apache.http.impl.io.AbstractSessionInputBuffer;
import org.apache.http.impl.io.HttpRequestParser;
import org.apache.http.io.HttpMessageParser;
import org.apache.http.io.SessionInputBuffer;
import org.apache.http.message.BasicHttpEntityEnclosingRequest;
import org.apache.http.message.BasicLineParser;
import org.apache.http.params.BasicHttpParams;

import java.io.ByteArrayInputStream;
import java.io.IOException;

/**
 *
 */
public class ApacheRequestFactory {
    public static HttpRequest create(final String requestAsString) {
        try {
            SessionInputBuffer inputBuffer = new AbstractSessionInputBuffer() {
                {
                    init(new ByteArrayInputStream(requestAsString.getBytes()), 10, new BasicHttpParams());
                }

                @Override
                public boolean isDataAvailable(int timeout) throws IOException {
                    throw new RuntimeException("have to override but probably not even called");
                }
            };
            HttpMessageParser parser = new HttpRequestParser(inputBuffer, new BasicLineParser(new ProtocolVersion("HTTP", 1, 1)), new DefaultHttpRequestFactory(), new BasicHttpParams());
            HttpMessage message = parser.parse();
            if (message instanceof BasicHttpEntityEnclosingRequest) {
                BasicHttpEntityEnclosingRequest request = (BasicHttpEntityEnclosingRequest) message;
                EntityDeserializer entityDeserializer = new EntityDeserializer(new LaxContentLengthStrategy());
                HttpEntity entity = entityDeserializer.deserialize(inputBuffer, message);
                request.setEntity(entity);
            }
            return (HttpRequest) message;
        } catch (IOException e) {
            throw new RuntimeException(e);
        } catch (HttpException e) {
            throw new RuntimeException(e);
        }
    }
}

以及显示如何使用它的测试类:

import org.apache.http.HttpRequest;
import org.apache.http.NameValuePair;
import org.apache.http.client.utils.URLEncodedUtils;
import org.apache.http.message.BasicHttpEntityEnclosingRequest;
import org.junit.Test;

import java.io.IOException;
import java.net.URI;
import java.util.List;

import static org.junit.Assert.*;

/**
 *
 */
public class ApacheRequestFactoryTest {
    @Test
    public void testGet() {
        String requestString = "GET /?one=aone&two=atwo HTTP/1.1\n" +
                "Host: localhost:7788\n" +
                "Connection: Keep-Alive\n" +
                "User-Agent: Apache-HttpClient/4.0.1 (java 1.5)";

        HttpRequest request = ApacheRequestFactory.create(requestString);
        assertEquals("GET", request.getRequestLine().getMethod());
        List<NameValuePair> pairs = URLEncodedUtils.parse(URI.create(request.getRequestLine().getUri()), "ISO-8859-1");
        checkPairs(pairs);
    }

    @Test
    public void testPost() throws IOException {
        String requestString = "POST / HTTP/1.1\n" +
                "Content-Length: 17\n" +
                "Content-Type: application/x-www-form-urlencoded; charset=ISO-8859-1\n" +
                "Host: localhost:7788\n" +
                "Connection: Keep-Alive\n" +
                "User-Agent: Apache-HttpClient/4.0.1 (java 1.5)\n" +
                "\n" +
                "one=aone&two=atwo";

        HttpRequest request = ApacheRequestFactory.create(requestString);
        assertEquals("POST", request.getRequestLine().getMethod());
        List<NameValuePair> pairs = URLEncodedUtils.parse(((BasicHttpEntityEnclosingRequest)request).getEntity());
        checkPairs(pairs);
    }

    private void checkPairs(List<NameValuePair> pairs) {
        for (NameValuePair pair : pairs) {
            if (pair.getName().equals("one")) assertEquals("aone", pair.getValue());
            else if (pair.getName().equals("two")) assertEquals("atwo", pair.getValue());
            else assertTrue("got more parameters than expected:"+pair.getName(), false);
        }
    }
}

小咆哮:

APACHE HTTP团队的想法是什么? api难以置信地使用起来很尴尬。世界各地的开发人员都在浪费时间编写包装器和转换类,以便每天使用磨机运行(例如,将字符串转换为apache http请求的简单操作,以及提取表单所需的奇怪方式参数(也必须以两种不同的方式进行,具体取决于请求的类型))。浪费的全球时间是巨大的。从底部开始编写API时,从规范开始,您必须从上到下开始一个层(顶部是一个接口,您可以在其中完成典型的工作,而无需了解或查看代码的实现方式),使每天使用图书馆方便直观。 Apache http库除了。它是这类任务的标准库几乎是一个奇迹。