首页
学习
活动
专区
圈层
工具
发布
首页
学习
活动
专区
圈层
工具
MCP广场
社区首页 >问答首页 >使用java se将httpRequest方法post提交到apache服务器。

使用java se将httpRequest方法post提交到apache服务器。
EN

Stack Overflow用户
提问于 2012-08-22 20:49:42
回答 1查看 338关注 0票数 0

我正在尝试使用java应用程序中的网站,就像通过浏览器一样;这是我第一次尝试这样的东西,我担心我遗漏了一些东西。

我使用apache httpcore库通过post方法处理http请求,使用wireshark我已经看到post请求中的参数,并将它们添加到我使用java处理的请求中;头文件也是如此。

如果我嗅探用java发出的请求,我不能捕获http post请求,只能捕获tcp流量。

我是这样做这个请求的:

代码语言:javascript
复制
HttpPost httpPost = new HttpPost("http://xxx.xxx");

httpPost.setHeader("Host", "xxx.xxx:xxxx");
.
.
.

HttpParams params = new BasicHttpParams();
params.setParameter("aaaa", "bbbb");
.
.
.

HttpResponse response = httpclient.execute(httpPost);

我是不是遗漏了什么?

我应该检查其他的东西吗?

非常感谢你的帮助!

EN

回答 1

Stack Overflow用户

发布于 2012-08-29 18:36:50

您必须为post请求提供一个主体,这是通过在HttpPost上调用.setEntity(HttpEntity)方法来实现的。

代码语言:javascript
复制
  private void sendToPostProxy(HttpServletRequest request,
          HttpServletResponse response) throws IOException {
      //the url to forward too
      String url = "http://127.0.0.1:"+proxyPort+request.getRequestURI()
              +(request.getQueryString()==null?"":"?"+request.getQueryString());
      HttpPost get = new HttpPost(url);
      //I am streaming requests straight through, but there are many Entity types you can use
      get.setEntity(new InputStreamEntity(request.getInputStream(), request.getContentLength()));
      sendToProxy(request, response, get);
  }
  private void sendToProxy(HttpServletRequest request,
          HttpServletResponse response,HttpRequestBase get) throws IOException {
    DefaultHttpClient client = new DefaultHttpClient();
    Enumeration headers = request.getHeaderNames();
    //copy headers
    while(headers.hasMoreElements()){
        String next = String.valueOf(headers.nextElement());
        String header = request.getHeader(next);
        if (!get.containsHeader(next)&&!"Content-Length".equalsIgnoreCase(next))
            get.addHeader(next, header);
    }
    try{
    //perform post
    HttpResponse proxied = client.execute(get);
    //set client headers
    for (Header h : proxied.getAllHeaders()){
        response.setHeader(h.getName(), h.getValue());
    }
    //stream to client
    HttpEntity body = proxied.getEntity();
    body.writeTo(response.getOutputStream());
    response.setStatus(HttpServletResponse.SC_OK);

    }catch(Exception e){
        e.printStackTrace();
        get.abort();
    }
}
票数 0
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/12073545

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档