weixin_36496775
2016-10-24 07:19
采纳率: 0%
浏览 1.1k

用java手写简单服务器,在浏览器上为什么会显示乱码

public class Service2 {
private ServerSocket server ;
private Socket socket;
private static final String crl="\r\n",bk=" ";

public static void main(String[] args) throws IOException {
    Service2 se=new Service2();
    se.start();
    se.receive();
}
public void start() throws IOException{
    server=new  ServerSocket(7879);
    socket =server.accept();
    System.out.println("建立了一个连接");
}
public void stop(){

}
public void receive() throws IOException{
    byte[]data=new byte[20480];
    int len=socket.getInputStream().read(data);
    String s =new String(data,0,len);
    System.out.println(s);

    StringBuilder responseContent=new  StringBuilder();
    responseContent.append("<html><head><title>响应界面</title></head><body>欢迎登陆响应界面</body></html>");

    StringBuilder response=new  StringBuilder();
    //1)http协议版本 ,状态代码,描述.
    response.append("HTTP/1.1").append(bk).append("200").append(bk).append("ok").append(crl);
    //2)响应头
    response.append("Server:mighu server/0.0.1").append(crl);
    response.append("Date:").append(new Date()).append(crl);
    //3)文件编码格式
    response.append("Content-Type:Text/html:charset=GBK").append(crl);
    response.append("Content-Length:").append(responseContent.toString().getBytes().length).append(crl).append(crl);
    response.append(responseContent.toString());

   DataOutputStream bw =new  DataOutputStream(socket.getOutputStream());
    bw.writeUTF(response.toString());
    bw.flush();
    bw.close();
}

}

  • 点赞
  • 写回答
  • 关注问题
  • 收藏
  • 邀请回答

1条回答 默认 最新

  • blownewbee 2016-10-24 07:21

    http://blog.csdn.net/mecho/article/details/7342654
    编码要和Content-Type的一样

    点赞 评论

相关推荐 更多相似问题