Daniel Oppong
Daniel Oppong

Reputation: 166

Java HttpURLConnection throwing Connection Reset exception

I'm beginning java network programming but I always get Connect Reset exception for the following code:

import java.io.*;
import java.net.*;
import java.util.*;

public class Net {

    public static void main() 
    {

        try
        {
            // this not working ...  URL url = new URL("http://localhost/test.php");

            // not even the following trial
            URL url = new URL("http://www.google.com.gh/");
            HttpURLConnection conn = (HttpURLConnection)url.openConnection();


            // Exception is thrown here
            InputStream in = conn.getInputStream();
        }

        catch (Exception ex)
        {
            System.out.println(ex.getMessage());
        }
    }
}

All examples I have tried in my learning process have failed. I don't know what is wrong. Help please.

Upvotes: 2

Views: 8019

Answers (1)

Simon
Simon

Reputation: 2733

Have you tries setting some additional info?

  conn.setRequestMethod("POST");
  conn.setRequestProperty("Content-Type", 
       "application/x-www-form-urlencoded");

  conn.setRequestProperty("Content-Length", "" + 
           Integer.toString(urlParameters.getBytes().length));
  conn.setRequestProperty("Content-Language", "en-US");  

  conn.setUseCaches (false);
  conn.setDoInput(true);
  conn.setDoOutput(true);


 DataOutputStream wr = new DataOutputStream (
              connection.getOutputStream ());
  wr.writeBytes (urlParameters);
  wr.flush ();
  wr.close ();


 The urlParameters is a URL encoded string.

 String urlParameters =
    "fName=" + URLEncoder.encode("???", "UTF-8") +
    "&lName=" + URLEncoder.encode("???", "UTF-8")

Upvotes: 1

Related Questions