ERR_INVALID_HTTP_RESPONSE
前段时间刚学完《Java网络编程》,最近着手学习《深入剖析Tomcat》,但是这里第一个案例就出现了问题。建议稍微有点网络基础的同学看。
书上源码多自己思考,根据已有知识排错。
请求头和请求体之间有一个空行。
响应头和响应体之火箭有一个空行
不细说了,参见net模块的笔记。
package chapter01.demo01;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.net.*;
import java.util.Objects;
/**
* @description HTTP服务器
* 阻塞的监听指定的应用程序,如果发现接收到请求就解析成Request
* 如果uri是关闭,就不再循环;否则将对应的uri资源封装成response返回
*
* @date:2022/11/3 15:52
* @author: qyl
*/
public class HttpServer {
// 指定资源路径
public static final String WEB_ROOT = Objects.requireNonNull(HttpServer.class.getClassLoader().getResource("webroot")).getPath();
private static final String SHUTDOWN_COMMAND = "/SHUTDOWN";
private boolean shutdown = false;
public static void main(String[] args) {
HttpServer server = new HttpServer();
server.await();
}
private void await() {
int port = 8080;
try (ServerSocket serverSocket = new ServerSocket(port, 1, InetAddress.getByName("127.0.0.1"))){
while (!shutdown) {
try (Socket socket = serverSocket.accept()) {
// 解析请求
InputStream input = socket.getInputStream();
Request request = new Request(input);
request.parse();
// 封装响应
OutputStream output = socket.getOutputStream();
Response response = new Response(output);
response.setRequest(request);
// 发送响应
response.sendStaticResource();
shutdown = request.getUri().endsWith(SHUTDOWN_COMMAND);
} catch (IOException e) {
e.printStackTrace();
}
}
} catch (IOException e) {
e.printStackTrace();
System.exit(1);
}
}
}
```java
package chapter01.demo01;
import java.io.*;
import java.net.URLConnection;
/**
* @description
* @date:2022/11/3 16:10
* @author: qyl
*/
public class Response {
private static final int BUFFER_SIZE = 1024;
Request request;
OutputStream output;
public Response(OutputStream output){
this.output = output;
}
public void setRequest(Request request){
this.request = request;
}
public void sendStaticResource() throws IOException {
byte[] bytes = new byte[BUFFER_SIZE];
FileInputStream fis = null;
try{
String filename = request.getUri();
File file = new File(HttpServer.WEB_ROOT,filename);
if (file.exists()){
String mimeType = URLConnection.getFileNameMap().getContentTypeFor(filename);
fis = new FileInputStream(file);
int ch ;
while ((ch = fis.read(bytes,0,BUFFER_SIZE)) != -1 ){
output.write(bytes,0,ch);
}
}else {
String errorMessage = "HTTP/1.1 404 File Not Found\r\n" +
"Content-Type: text/html\r\n" +
"Content-Length:23\r\n"+
"\r\n"+
"<h1>File Not Found</h1>";
output.write(errorMessage.getBytes());
}
} catch (IOException e) {
e.printStackTrace();
}finally {
if (fis != null){
fis.close();
}
}
}
}
package chapter01.demo01;
import java.io.IOException;
import java.io.InputStream;
/**
* @description
* @date:2022/11/3 16:01
* @author: qyl
*/
public class Request {
private InputStream input;
private String uri;
public Request(InputStream input) {
this.input = input;
}
public void parse() {
StringBuilder request = new StringBuilder(2048);
int i;
byte[] buffer = new byte[2048];
try {
i = input.read(buffer);
} catch (IOException e) {
e.printStackTrace();
i = -1;
}
for (int j = 0; j < i; j++) {
request.append((char)buffer[j]);
}
System.out.println(request.toString());
uri = parseUri(request.toString());
}
private String parseUri(String requestString) {
int index1,index2;
index1 = requestString.indexOf(' ');
if (index1 != -1){
index2 = requestString.indexOf(' ' ,index1+1);
if (index2 > index1){
return requestString.substring(index1+1,index2);
}
}
return null;
}
public String getUri() {
return uri;
}
}
之后启动HttpServer,并且打开浏览器输入http://localhost:8080/index.html出现了如下错误:

明确表示了响应无效,根据前置知识:请求成功解析并封装,那么我们查看Response类。
有两种可能
文件找不到,我们的错误响应写错了。即如下这代码:

故进行如下测试,发现没有问题:

找到了文件,但是响应写错了。即如下代码

其实很明显就有问题,根据前置知识,这里只有响应体,没有响应头。
添加响应头内容,进行测试,成功解决。

package chapter01.demo01;
import java.io.*;
import java.net.URLConnection;
/**
* @description
* @date:2022/11/3 16:10
* @author: qyl
*/
public class Response {
private static final int BUFFER_SIZE = 1024;
Request request;
OutputStream output;
public Response(OutputStream output){
this.output = output;
}
public void setRequest(Request request){
this.request = request;
}
public void sendStaticResource() throws IOException {
byte[] bytes = new byte[BUFFER_SIZE];
FileInputStream fis = null;
try{
String filename = request.getUri();
File file = new File(HttpServer.WEB_ROOT,filename);
if (file.exists()){
String mimeType = URLConnection.getFileNameMap().getContentTypeFor(filename);
String header = "HTTP/1.1 200 OK\r\n"
+ "Server: OneFile 2.0\r\n"
+ "Content-type: " + mimeType + ";\r\n\r\n";
output.write(header.getBytes());
fis = new FileInputStream(file);
int ch ;
while ((ch = fis.read(bytes,0,BUFFER_SIZE)) != -1 ){
output.write(bytes,0,ch);
}
}else {
String errorMessage = "HTTP/1.1 404 File Not Found\r\n" +
"Content-Type: text/html\r\n" +
"Content-Length:23\r\n"+
"\r\n"+
"<h1>File Not Found</h1>";
output.write(errorMessage.getBytes());
}
} catch (IOException e) {
e.printStackTrace();
}finally {
if (fis != null){
fis.close();
}
}
}
}
是的,我知道最好使用webmock,但我想知道如何在RSpec中模拟此方法:defmethod_to_testurl=URI.parseurireq=Net::HTTP::Post.newurl.pathres=Net::HTTP.start(url.host,url.port)do|http|http.requestreq,foo:1endresend这是RSpec:let(:uri){'http://example.com'}specify'HTTPcall'dohttp=mock:httpNet::HTTP.stub!(:start).and_yieldhttphttp.shou
我目前正在使用以下方法获取页面的源代码:Net::HTTP.get(URI.parse(page.url))我还想获取HTTP状态,而无需发出第二个请求。有没有办法用另一种方法做到这一点?我一直在查看文档,但似乎找不到我要找的东西。 最佳答案 在我看来,除非您需要一些真正的低级访问或控制,否则最好使用Ruby的内置Open::URI模块:require'open-uri'io=open('http://www.example.org/')#=>#body=io.read[0,50]#=>"["200","OK"]io.base_ur
1.错误信息:Errorresponsefromdaemon:Gethttps://registry-1.docker.io/v2/:net/http:requestcanceledwhilewaitingforconnection(Client.Timeoutexceededwhileawaitingheaders)或者:Errorresponsefromdaemon:Gethttps://registry-1.docker.io/v2/:net/http:TLShandshaketimeout2.报错原因:docker使用的镜像网址默认为国外,下载容易超时,需要修改成国内镜像地址(首先阿里
目录1.漏洞简介2、AJP13协议介绍Tomcat主要有两大功能:3.Tomcat远程文件包含漏洞分析4.漏洞复现 5、漏洞分析6.RCE实现的原理1.漏洞简介2020年2月20日,公开CNVD的漏洞公告中发现ApacheTomcat文件包含漏洞(CVE-2020-1938)。ApacheTomcat是Apache开源组织开发的用于处理HTTP服务的项目。ApacheTomcat服务器中被发现存在文件包含漏洞,攻击者可利用该漏洞读取或包含Tomcat上所有webapp目录下的任意文件。该漏洞是一个单独的文件包含漏洞,依赖于Tomcat的AJP(定向包协议)。AJP自身存在一定缺陷,导致存在可控
Rails中有没有一种方法可以提取与路由关联的HTTP动词?例如,给定这样的路线:将“users”匹配到:“users#show”,通过:[:get,:post]我能实现这样的目标吗?users_path.respond_to?(:get)(显然#respond_to不是正确的方法)我最接近的是通过执行以下操作,但它似乎并不令人满意。Rails.application.routes.routes.named_routes["users"].constraints[:request_method]#=>/^GET$/对于上下文,我有一个设置cookie然后执行redirect_to:ba
我正在使用Heroku(heroku.com)来部署我的Rails应用程序,并且正在构建一个iPhone客户端来与之交互。我的目的是将手机的唯一设备标识符作为HTTPheader传递给应用程序以进行身份验证。当我在本地测试时,我的header通过得很好,但在Heroku上它似乎去掉了我的自定义header。我用ruby脚本验证:url=URI.parse('http://#{myapp}.heroku.com/')#url=URI.parse('http://localhost:3000/')req=Net::HTTP::Post.new(url.path)#boguspara
我试图在我的网站上实现使用Facebook登录功能,但在尝试从Facebook取回访问token时遇到障碍。这是我的代码:ifparams[:error_reason]=="user_denied"thenflash[:error]="TologinwithFacebook,youmustclick'Allow'toletthesiteaccessyourinformation"redirect_to:loginelsifparams[:code]thentoken_uri=URI.parse("https://graph.facebook.com/oauth/access_token
我是Ruby的新手。我试过查看在线文档,但没有找到任何有效的方法。我想在以下HTTP请求botget_response()和get()中包含一个用户代理。有人可以指出我正确的方向吗?#PreliminarycheckthatProggitisupcheck=Net::HTTP.get_response(URI.parse(proggit_url))ifcheck.code!="200"puts"ErrorcontactingProggit"returnend#Attempttogetthejsonresponse=Net::HTTP.get(URI.parse(proggit_url)
我正在尝试解析网页,但有时会收到404错误。这是我用来获取网页的代码:result=Net::HTTP::getURI.parse(URI.escape(url))如何测试result是否为404错误代码? 最佳答案 像这样重写你的代码:uri=URI.parse(url)result=Net::HTTP.start(uri.host,uri.port){|http|http.get(uri.path)}putsresult.codeputsresult.body这将打印状态码和正文。
我正在安装gitlabhq,并且在Gemfile中有对某些资源的“git://...”的引用。但是,我在公司防火墙后面,所以我必须使用http://。我可以手动编辑Gemfile,但我想知道是否有另一种方法告诉bundler使用http://作为git存储库? 最佳答案 您可以通过运行gitconfig--globalurl."https://".insteadOfgit://或通过将以下内容添加到~/.gitconfig:[url"https://"]insteadOf=git://