在Java HttpServer响应中设置内容类型 [英] Setting Content Type in Java HttpServer response

查看:113
本文介绍了在Java HttpServer响应中设置内容类型的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个Java echo httpserver了.

I have a java echo httpserver up.

它适用于测试站点,但是我正在使用的客户端代码无法获取数据.

It works with test sites, but the client code I'm working with fails to get the data.

服务器与 https://www.hurl.it/

客户端与 https://requestb.in/将两者结合在一起时,我得到一个状态码为200的响应,但是即使正在发送,客户端中也没有显示元数据/正文内容.

When combining the two I get a response with a status code of 200, but no metadata / body content shows up in the client even though it's being sent.

我唯一的猜测是因为不包括内容类型,客户端对此可能会很挑剔.

My only guess is because the content type isn't included, the client might be picky about that.

如何在回复中指定内容类型?

How can i specify the content type in my response?

(注意,客户端使用POST作为参数向服务器发送单个字符串以及一些标头信息.此代码当前设置为仅返回正文内容/参数.)

(A note, the client sends a single string to the server with a POST as a parameter along with some header info. This code is currently setup to only return the body content/parameter.)

任何想法表示赞赏!

import static java.net.HttpURLConnection.HTTP_OK;

import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.net.InetSocketAddress;
import java.net.URLDecoder;
import java.util.List;

import com.sun.net.httpserver.Headers;
import com.sun.net.httpserver.HttpExchange;
import com.sun.net.httpserver.HttpHandler;
import com.sun.net.httpserver.HttpServer;

/**
* Echo the body of an HTTP request back as the HTTP response. This is merely
* a simple exercise of the Secret Sun Web Server. As configured, the URL to
* access it is http://localhost:8000/echo.
* 
* @author Andrew Cowie
*/
public final class Test
{
public static void main(String[] args) throws IOException {
    final InetSocketAddress addr;
    final HttpServer server;

    addr = new InetSocketAddress(8000);

    server = HttpServer.create(addr, 10);
    server.createContext("/echo", new EchoHandler());
    server.start();
}
}

class EchoHandler implements HttpHandler
{
public void handle(HttpExchange t) throws IOException {
    final InputStream is;
    final OutputStream os;
    StringBuilder buf;
    int b;
    final String request, response;

    buf = new StringBuilder();

    /*
     * Get the request body and decode it. Regardless of what you are
     * actually doing, it is apparently considered correct form to consume
     * all the bytes from the InputStream. If you don't, closing the
     * OutputStream will cause that to occur
     */

    is = t.getRequestBody();

    while ((b = is.read()) != -1) {
        buf.append((char) b);
    }

    is.close();

    if (buf.length() > 0) {
        request = URLDecoder.decode(buf.toString(), "UTF-8");
    } else {
        request = null;
    }

    /*
     * Construct our response:
     */

    buf = new StringBuilder();
    //buf.append("<html><head><title>HTTP echo server</title></head><body>");
    //buf.append("<p><pre>");
    //buf.append(t.getRequestMethod() + " " + t.getRequestURI() + " " + t.getProtocol() + "\n");

    /*
     * Process the request headers. This is a bit involved due to the
     * complexity arising from the fact that headers can be repeated.
     */

    Headers headers = t.getRequestHeaders();

    for (String name : headers.keySet()) {
        List<String> values = headers.get(name);

        for (String value : values) {
            //buf.append(name + ": " + value + "\n");
        }
    }

    /*
     * If there was an actual body to the request, add it:
     */

    if (request != null) {
        //buf.append("\n");
        buf.append(request);
    }

    //buf.append("</pre></p>");
    //buf.append("</body></html>\n");

    response = buf.toString();
    System.out.println(response);

    /*
     * And now send the response. We could have instead done this
     * dynamically, using 0 as the response size (forcing chunked
     * encoding) and writing the bytes of the response directly to the
     * OutputStream, but building the String first allows us to know the
     * exact length so we can send a response with a known size. Better :)
     */

    t.sendResponseHeaders(HTTP_OK, response.length());

    os = t.getResponseBody();

    os.write(response.getBytes());

    /*
     * And we're done!
     */

    os.close();
    t.close();
}

}

推荐答案

尝试添加

t.getResponseHeaders().put("Content-Type", "text/html"); 

写之前

这篇关于在Java HttpServer响应中设置内容类型的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆