gpt4 book ai didi

java - HTTP 客户端不工作

转载 作者:行者123 更新时间:2023-12-01 18:54:30 26 4
gpt4 key购买 nike

我正在尝试构建一个简单的 HTTP 客户端程序,它将请求发送到 Web 服务器并将响应打印给用户。

当我运行代码时,出现以下错误,但我不确定是什么原因导致的:

<强>-1线程“main”中的异常 java.lang.IllegalArgumentException:端口超出范围:-1 在 java.net.InetSocketAddress.(InetSocketAddress.java:118) 在 java.net.Socket.(Socket.java:189) 在 com.example.bookstore.MyHttpClient.execute(MyHttpClient.java:18) 在 com.example.bookstore.MyHttpClientApp.main(MyHttpClientApp.java:29)Java 结果:1

下面是我的 MyHttpClient.java 类

public class MyHttpClient {

MyHttpRequest request;

public MyHttpResponse execute(MyHttpRequest request) throws IOException {

this.request = request;

int port = request.getPort();
System.out.println(port);

//Create a socket
Socket s = new Socket(request.getHost(), request.getPort());
//Create I/O streams
BufferedReader inFromServer = new BufferedReader(new InputStreamReader(s.getInputStream()));
PrintWriter outToServer = new PrintWriter(s.getOutputStream());
//Get method (POST OR GET) from request
String method = request.getMethod();

//Create response
MyHttpResponse response = new MyHttpResponse();

//GET Request
if(method.equalsIgnoreCase("GET")){
//Construct request line
String path = request.getPath();
String queryString = request.getQueryString();
//Send request line to server
outToServer.println("GET " + path + " HTTP/1.0");

//=================================================\\

//HTTP RESPONSE

//RESPONSE LINE

//Read response from server
String line = inFromServer.readLine();
//Get response code - should be 200.
int status = Integer.parseInt(line.substring(9, 3));
//Get text description of response code - if 200 should be OK.
String desc = line.substring(13);

//HEADER LINES

//Loop through headers until get to blank line...
//Header name: Header Value - structure
do{
line = inFromServer.readLine();
if(line != null && line.length() == 0){
//line is not blank
//header name start of line to the colon.
String name = line.substring(0, line.indexOf(": "));
//header value after the colon to end of line.
String value = String.valueOf(line.indexOf(": "));
response.addHeader(name, value);
}
}while(line != null && line.length() == 0);


//MESSAGE BODY
StringBuilder sb = new StringBuilder();
do{
line = inFromServer.readLine();
if(line != null){
sb.append((line)+"\n");
}
}while(line != null);

String body = sb.toString();
response.setBody(body);

//return response
return response;
}

//POST Request
else if(method.equalsIgnoreCase("POST")){
return response;

}
return response;
}

}

这是 MyHttpClientApp.java 类

public class MyHttpClientApp {

public static void main(String[] args) {
String urlString = null;
URI uri;
MyHttpClient client;
MyHttpRequest request;
MyHttpResponse response;

try {
//==================================================================
// send GET request and print response
//==================================================================
urlString = "http://127.0.0.1/bookstore/viewBooks.php";
uri = new URI(urlString);

client = new MyHttpClient();



request = new MyHttpRequest(uri);
request.setMethod("GET");
response = client.execute(request);

System.out.println("=============================================");
System.out.println(request);
System.out.println("=============================================");
System.out.println(response);
System.out.println("=============================================");

}
catch (URISyntaxException e) {
String errorMessage = "Error parsing uri (" + urlString + "): " + e.getMessage();
System.out.println("MyHttpClientApp: " + errorMessage);
}
catch (IOException e) {
String errorMessage = "Error downloading book list: " + e.getMessage();
System.out.println("MyHttpClientApp: " + errorMessage);
}
}

}

MyHttpRequest

public class MyHttpRequest {

private URI uri;
private String method;
private Map<String, String> params;

public MyHttpRequest(URI uri) {
this.uri = uri;
this.method = null;
this.params = new HashMap<String, String>();
}

public String getHost() {
return this.uri.getHost();
}

public int getPort() {
return this.uri.getPort();
}

public String getPath() {
return this.uri.getPath();
}

public void addParameter(String name, String value) {
try {
name = URLEncoder.encode(name, "UTF-8");
value = URLEncoder.encode(value, "UTF-8");
this.params.put(name, value);
}
catch (UnsupportedEncodingException ex) {
System.out.println("URL encoding error: " + ex.getMessage());
}
}

public Map<String, String> getParameters() {
return this.params;
}

public String getQueryString() {
Map<String, String> parameters = this.getParameters();
// construct StringBuffer with name/value pairs
Set<String> names = parameters.keySet();
StringBuilder sbuf = new StringBuilder();
int i = 0;
for (String name : names) {
String value = parameters.get(name);
if (i != 0) {
sbuf.append("&");
}
sbuf.append(name);
sbuf.append("=");
sbuf.append(value);
i++;
}

return sbuf.toString();
}

public String getMethod() {
return method;
}

public void setMethod(String method) {
this.method = method;
}

@Override
public String toString() {
StringBuilder sbuf = new StringBuilder();

sbuf.append(this.getMethod());
sbuf.append(" ");
sbuf.append(this.getPath());
if (this.getMethod().equals("GET")) {
if (this.getQueryString().length() > 0) {
sbuf.append("?");
sbuf.append(this.getQueryString());
}
sbuf.append("\n");
sbuf.append("\n");
}
else if (this.getMethod().equals("POST")) {
sbuf.append("\n");
sbuf.append("\n");
sbuf.append(this.getQueryString());
sbuf.append("\n");
}

return sbuf.toString();
}

}

MyHttpResponse

public class MyHttpResponse {

private int status;
private String description;
private Map<String, String> headers;
private String body;

public MyHttpResponse() {
this.headers = new HashMap<String, String>();
}

public int getStatus() {
return this.status;
}

public void setStatus(int status) {
this.status = status;
}

public String getDescription() {
return this.description;
}

public void setDescription(String description) {
this.description = description;
}

public Map<String, String> getHeaders() {
return this.headers;
}

public void addHeader(String header, String value) {
headers.put(header, value);
}

public String getBody() {
return body;
}

public void setBody(String is) {
this.body = is;
}

@Override
public String toString() {
StringBuilder sbuf = new StringBuilder();

sbuf.append("Http Response status line: ");
sbuf.append("\n");
sbuf.append(this.getStatus());
sbuf.append(" ");
sbuf.append(this.getDescription());
sbuf.append("\n");
sbuf.append("---------------------------------------------");
sbuf.append("\n");
sbuf.append("Http Response headers: ");
sbuf.append("\n");
for (String key: this.getHeaders().keySet()) {
String value = this.getHeaders().get(key);
sbuf.append(key);
sbuf.append(": ");
sbuf.append(value);
sbuf.append("\n");
}
sbuf.append("---------------------------------------------");
sbuf.append("\n");
sbuf.append("Http Response body: ");
sbuf.append("\n");
sbuf.append(this.getBody());
sbuf.append("\n");

return sbuf.toString();
}

}

有什么想法可能会发生什么吗?非常感谢。

最佳答案

我猜您的请求没有明确指定端口,因此您的 request.getPort() 返回 -1。然后你尝试连接到端口-1。这是非法的。

相反,在使用端口之前:检查它是否 <= 0,在本例中使用 80 作为默认值。

int port = request.getPort();
if(port<=0) port=80;

关于java - HTTP 客户端不工作,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/14562957/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com