Warning: file_get_contents(/data/phpspider/zhask/data//catemap/8/http/4.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Java HTTP客户端不工作_Java_Http_Netbeans_Httpclient_Illegalargumentexception - Fatal编程技术网

Java HTTP客户端不工作

Java HTTP客户端不工作,java,http,netbeans,httpclient,illegalargumentexception,Java,Http,Netbeans,Httpclient,Illegalargumentexception,我正在尝试构建一个简单的HTTP客户端程序,它将请求发送到web服务器并将响应打印给用户 我在运行代码时出现以下错误,我不确定是什么原因造成的: -1 线程“main”java.lang.IllegalArgumentException中出现异常:端口超出范围:-1 位于java.net.InetSocketAddress。(InetSocketAddress.java:118) 位于java.net.Socket(Socket.java:189) 位于com.example.bookstore

我正在尝试构建一个简单的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;
}
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);
    }
}
}

这是MyHttpClientApp.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;
}
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();
}
公共类MyHttpRequest{
私有URI;
私有字符串方法;
私有映射参数;
公共MyHttpRequest(URI){
this.uri=uri;
this.method=null;
this.params=new HashMap();
}
公共字符串getHost(){
返回这个.uri.getHost();
}
公共int getPort(){
返回这个.uri.getPort();
}
公共字符串getPath(){
返回这个.uri.getPath();
}
public void addParameter(字符串名称、字符串值){
试一试{
name=URLEncoder.encode(名称,“UTF-8”);
value=URLEncoder.encode(值为“UTF-8”);
this.params.put(名称、值);
}
捕获(不支持DencodingException ex){
System.out.println(“URL编码错误:+ex.getMessage());
}
}
公共映射getParameters(){
返回此.params;
}
公共字符串getQueryString(){
映射参数=this.getParameters();
//使用名称/值对构造StringBuffer
Set name=parameters.keySet();
StringBuilder sbuf=新的StringBuilder();
int i=0;
for(字符串名称:名称){
字符串值=参数.get(名称);
如果(i!=0){
sbuf.追加(“&”);
}
sbuf.append(名称);
sbuf.追加(“=”);
附加(值);
i++;
}
返回sbuf.toString();
}
公共字符串getMethod(){
返回法;
}
公共void集合方法(字符串方法){
这个方法=方法;
}
@凌驾
公共字符串toString(){
StringBuilder sbuf=新的StringBuilder();
sbuf.append(this.getMethod());
sbuf.追加(“”);
追加(this.getPath());
if(this.getMethod().equals(“GET”)){
if(this.getQueryString().length()>0){
sbuf.追加(“?”);
追加(this.getQueryString());
}
sbuf.append(“\n”);
sbuf.append(“\n”);
}
else if(this.getMethod().equals(“POST”)){
sbuf.append(“\n”);
sbuf.append(“\n”);
追加(this.getQueryString());
sbuf.append(“\n”);
}
返回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();
}
公共类MyHttpResponse{
私人身份;
私有字符串描述;
私有映射头;
私有字符串体;
公共MyHttpResponse(){
this.headers=new HashMap();
}
public int getStatus(){
返回此状态;
}
公共无效设置状态(int状态){
这个状态=状态;
}
公共字符串getDescription(){
返回此.description;
}
公共void集合描述(字符串描述){
this.description=描述;
}
公共映射getHeaders(){
返回此.headers;
}
public void addHeader(字符串头,字符串值){
headers.put(header,value);
}
公共字符串getBody(){
返回体;
}
public void setBody(字符串为){
this.body=is;
}
@凌驾
公共字符串toString(){
StringBuilder sbuf=新的StringBuilder();
追加(“Http响应状态行:”);
sbuf.append(“\n”);
sbuf.append(this.getStatus());
sbuf.追加(“”);
sbuf.append(this.getDescription());
sbuf.append(“\n”);
sbuf.追加(“-------------------------------------------------------------”;
sbuf.append(“\n”);
append(“Http响应头:”);
sbuf.append(“\n”);
for(字符串键:this.getHeaders().keySet()){
字符串值=this.getHeaders().get(键);
sbuf.append(键);
sbuf.追加(“:”);
附加(值);
sbuf.append(“\n”);
}
sbuf.追加(“-------------------------------------------------------------”;
sbuf.append(“\n”);
append(“Http响应体:”);
sbuf.append(“\n”);
sbuf.append(this.getBody());
sbuf.append(“\n”);
返回sbuf.toString();
}
}


你知道会发生什么吗?非常感谢。

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


相反,在使用端口之前:检查它是否我猜您的请求没有显式指定端口,因此您的请求.getPort()返回-1。然后尝试连接到端口-1。这是非法的


相反,在使用端口之前:检查它是否正在大量重新创建轮子。为什么不使用Java内置的HTTP客户机(至少,还有许多第三方HTTP客户机做得很好)


诸如此类。

这里正在进行大量的车轮再造。为什么不使用Java内置的HTTP客户机(至少,还有许多第三方HTTP客户机做得很好)

等等。

使用

    uri = URIUtil.encodeQuery(urlString)
反而

    uri = new URI(urlString); 
使用

反而

    uri = new URI(urlString); 

由于URI中没有设置端口,因此从javadocs开始,从端口返回-1:


由于URI中没有设置端口,因此从javadocs开始,从端口返回-1:


你的
端口
变量中有什么?你的
端口
变量中有什么?我应该提到,我这样做是作为我大学网络模块的一部分。因此,我们的想法是了解默认http客户机将如何工作!我应该提到的是,我做这件事是作为我大学网络模块的一部分。因此,我们的想法是了解默认http客户机将如何工作!