Sign Up

Sign Up to our social questions and Answers Engine to ask questions, answer people’s questions, and connect with other people.

Have an account? Sign In

Have an account? Sign In Now

Sign In

Login to our social questions & Answers Engine to ask questions answer people’s questions & connect with other people.

Sign Up Here

Forgot Password?

Don't have account, Sign Up Here

Forgot Password

Lost your password? Please enter your email address. You will receive a link and will create a new password via email.

Have an account? Sign In Now

You must login to ask a question.

Forgot Password?

Need An Account, Sign Up Here

Please briefly explain why you feel this question should be reported.

Please briefly explain why you feel this answer should be reported.

Please briefly explain why you feel this user should be reported.

Sign InSign Up

The Archive Base

The Archive Base Logo The Archive Base Logo

The Archive Base Navigation

  • SEARCH
  • Home
  • About Us
  • Blog
  • Contact Us
Search
Ask A Question

Mobile menu

Close
Ask a Question
  • Home
  • Add group
  • Groups page
  • Feed
  • User Profile
  • Communities
  • Questions
    • New Questions
    • Trending Questions
    • Must read Questions
    • Hot Questions
  • Polls
  • Tags
  • Badges
  • Buy Points
  • Users
  • Help
  • Buy Theme
  • SEARCH
Home/ Questions/Q 9207203
In Process

The Archive Base Latest Questions

Editorial Team
  • 0
Editorial Team
Asked: June 18, 20262026-06-18T00:20:15+00:00 2026-06-18T00:20:15+00:00

I am trying to build a simple HTTP client program that sends a request

  • 0

I am trying to build a simple HTTP client program that sends a request to a web server and prints the response out to the user.

I have got the following error when I run my code and I am not sure what is causing it:

-1
Exception in thread “main” java.lang.IllegalArgumentException: port out of range:-1
at java.net.InetSocketAddress.(InetSocketAddress.java:118)
at java.net.Socket.(Socket.java:189)
at com.example.bookstore.MyHttpClient.execute(MyHttpClient.java:18)
at com.example.bookstore.MyHttpClientApp.main(MyHttpClientApp.java:29)
Java Result: 1

Below is my MyHttpClient.java class

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;
}

}

This is the MyHttpClientApp.java class

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();
}

}

Any ideas what might be happening? Many thanks in advance.

  • 1 1 Answer
  • 0 Views
  • 0 Followers
  • 0
Share
  • Facebook
  • Report

Leave an answer
Cancel reply

You must login to add an answer.

Forgot Password?

Need An Account, Sign Up Here

1 Answer

  • Voted
  • Oldest
  • Recent
  • Random
  1. Editorial Team
    Editorial Team
    2026-06-18T00:20:16+00:00Added an answer on June 18, 2026 at 12:20 am

    I guess your request don’t specify a port explicitly and so your request.getPort() is returning -1. And then you try to connect to port -1. And this is illegal.

    Instead of that, before using the port : check if it is <= 0 and in this case use 80 as default value.

    int port = request.getPort();
    if(port<=0) port=80;
    
    • 0
    • Reply
    • Share
      Share
      • Share on Facebook
      • Share on Twitter
      • Share on LinkedIn
      • Share on WhatsApp
      • Report

Sidebar

Related Questions

i am trying to build simple web server, that able to transfer files. I
I'm trying to build a simple multithreaded tcp server. The client connects and sends
When trying to build a simple test program that uses atomic operations, I get
I'm trying to build a simple HTTP Server using Java, using java.net.ServerSocket = new
I'm trying to use the new System.Net.Http bits to build a simple HTTP client
I was trying to build a 'site search' on a simple http site. I
I'm trying to build a simple user setting feature for my school project. I've
I'm trying to build a simple application, with the finished program looking like this
I am trying to build a simple java program which creates a db file,
I'm trying to develop an agent/client that will listen to HTTP requests on a

Explore

  • Home
  • Add group
  • Groups page
  • Communities
  • Questions
    • New Questions
    • Trending Questions
    • Must read Questions
    • Hot Questions
  • Polls
  • Tags
  • Badges
  • Users
  • Help
  • SEARCH

Footer

© 2021 The Archive Base. All Rights Reserved
With Love by The Archive Base

Insert/edit link

Enter the destination URL

Or link to existing content

    No search term specified. Showing recent items. Search or use up and down arrow keys to select an item.