Java HttpURLConnection抛出连接重置异常

时间:2013-11-24 10:01:03

标签: java httpurlconnection connection-reset

我正在开始java网络编程,但我总是得到以下代码的Connect Reset异常:

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

我在学习过程中尝试过的所有例子都失败了。我不知道出了什么问题。请帮助。

1 个答案:

答案 0 :(得分:1)

您是否尝试过设置其他信息?

  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")