java Apache HttpCore,简单的服务器来回显收到的帖子数据

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/7199969/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-10-30 19:02:54  来源:igfitidea点击:

Apache HttpCore, simple server to echo received post data

javahttppostapache-httpcomponents

提问by Zugdud

Using the ElementalHttpServer example class found here:

使用此处找到的 ElementalHttpServer 示例类:

https://hc.apache.org/httpcomponents-core-4.3.x/httpcore/examples/org/apache/http/examples/ElementalHttpServer.java

https://hc.apache.org/httpcomponents-core-4.3.x/httpcore/examples/org/apache/http/examples/ElementalHttpServer.java

I am able to successfully receive post data, my goal is to convert the received post data into a string I can print. I've modified the HttpFileHandler as follows, using eneity.getContent() to get the inputStream, but i'm not sure how I can convert the inputStream into a String.

我能够成功接收帖子数据,我的目标是将收到的帖子数据转换为我可以打印的字符串。我修改了 HttpFileHandler 如下,使用 eneity.getContent() 来获取 inputStream,但我不确定如何将 inputStream 转换为 String。

static class HttpFileHandler implements HttpRequestHandler  {

  private final String docRoot;

  public HttpFileHandler(final String docRoot) {
    super();
    this.docRoot = docRoot;
  }

  public void handle(
        final HttpRequest request, 
        final HttpResponse response,
        final HttpContext context) throws HttpException, IOException {

    String method = request.getRequestLine().getMethod().toUpperCase(Locale.ENGLISH);
    if (!method.equals("GET") && !method.equals("HEAD") && !method.equals("POST")) {
        throw new MethodNotSupportedException(method + " method not supported"); 
    }
    String target = request.getRequestLine().getUri();

    if (request instanceof HttpEntityEnclosingRequest) {
        HttpEntity entity = ((HttpEntityEnclosingRequest) request).getEntity();
        byte[] entityContent = EntityUtils.toByteArray(entity);
        InputStream inputStream = entity.getContent();

        String str= inputStream.toString();
        byte[] b3=str.getBytes();
        String st = new String(b3);
        System.out.println(st);
        for(int i=0;i<b3.length;i++) {
         System.out.print(b3[i]+"\t");
        }
        System.out.println("Incoming entity content (bytes): " + entityContent.length);
    }
}

}

}

Thanks for any ideas

感谢您的任何想法

回答by omnomnom

Here is simple console logging handler; it logs every request (not only POST) - both headers and payload:

这是简单的控制台日志处理程序;它记录每个请求(不仅是 POST)——标头和有效负载:

package com.mycompany;

import org.apache.http.*;
import org.apache.http.entity.StringEntity;
import org.apache.http.protocol.HttpContext;
import org.apache.http.protocol.HttpRequestHandler;
import org.apache.http.util.EntityUtils;
import org.omg.CORBA.Request;

import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;

/**
 * Created by IntelliJ IDEA.
 * User: Piotrek
 * To change this template use File | Settings | File Templates.
 */
public class LoggingHandler implements HttpRequestHandler {
    public void handle(HttpRequest httpRequest, HttpResponse httpResponse, HttpContext httpContext) throws HttpException, IOException {

        System.out.println(""); // empty line before each request
        System.out.println(httpRequest.getRequestLine());
        System.out.println("-------- HEADERS --------");
        for(Header header: httpRequest.getAllHeaders()) {
            System.out.println(header.getName() + " : " + header.getValue());
        }
        System.out.println("--------");

        HttpEntity entity = null;
        if (httpRequest instanceof HttpEntityEnclosingRequest)
            entity = ((HttpEntityEnclosingRequest)httpRequest).getEntity();

        // For some reason, just putting the incoming entity into
        // the response will not work. We have to buffer the message.
        byte[] data;
        if (entity == null) {
            data = new byte [0];
        } else {
            data = EntityUtils.toByteArray(entity);
        }

        System.out.println(new String(data));

        httpResponse.setEntity(new StringEntity("dummy response"));
    }
}

Registration of handler using org.apache.http.localserver.LocalTestServer(with ElementalHttpServerit is similar - you also have HttpRequestHandlerimplementation above):

使用注册处理程序org.apache.http.localserver.LocalTestServer(与ElementalHttpServer它类似 - 你也有HttpRequestHandler上面的实现):

 public static void main(String[] args) throws Exception {
    LocalTestServer server = new LocalTestServer(null, null);

    try {
        server.start();      

        server.register("/*", new LoggingHandler());
        server.awaitTermination(3600 * 1000);

    } catch (Exception e) {
        e.printStackTrace();
    } finally {
        server.stop();
    }

}