2

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.

Jonik
  • 80,077
  • 70
  • 264
  • 372
Daniel Oppong
  • 158
  • 1
  • 10
  • Is there a proxy defined when you're just browsing on this particular PC? If so you'll ofcourse need to define the proxy in your code as well. See [this question](http://stackoverflow.com/questions/1432961/how-do-i-make-httpurlconnection-use-a-proxy/1433296#1433296) – NickDK Nov 24 '13 at 10:04
  • no proxy NickDK. It's a direct connection. – Daniel Oppong Nov 24 '13 at 10:07
  • Works good for me (with a little correction). maybe a permissions issue? – MeNa Nov 24 '13 at 10:19
  • probably, but can't guess what that could be. – Daniel Oppong Nov 24 '13 at 10:27
  • Your code works just fine for me. Indeed looks like some local connectivity problem. Do you get the same result using any publicly accessible url? – Jonik Nov 24 '13 at 10:53
  • Yes, the code above accesses google website as a try which is available but my code throws exception with message Connection Reset. – Daniel Oppong Nov 24 '13 at 10:55

1 Answers1

1

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")
Simon
  • 2,643
  • 3
  • 40
  • 61