Eclipse中的openConnection()的UnknownHostException和未知来源

时间:2013-09-30 15:46:23

标签: java eclipse connection httpurlconnection unknown-host

我是网站上的新用户。我的问题如下:

我在Eclipse工具中有一个java项目。实际上,它是一个java服务器,它必须解析Web中的数据并在模拟登录同一Web之后。我用Android手机(客户端)发送消息(tipical client-server app)来激活这个服务器。所有这一切都与本地wifi连接完成。问题是:

Exception in thread "main" java.net.UnknownHostException: larrun.iberdrola.es
at java.net.AbstractPlainSocketImpl.connect(Unknown Source)
at java.net.PlainSocketImpl.connect(Unknown Source)
at java.net.SocksSocketImpl.connect(Unknown Source)
at java.net.Socket.connect(Unknown Source)
at sun.security.ssl.SSLSocketImpl.connect(Unknown Source)
at sun.security.ssl.BaseSSLSocketImpl.connect(Unknown Source)
at sun.net.NetworkClient.doConnect(Unknown Source)
at sun.net.www.http.HttpClient.openServer(Unknown Source)
at sun.net.www.http.HttpClient.openServer(Unknown Source)
at sun.net.www.protocol.https.HttpsClient.<init>(Unknown Source)
at sun.net.www.protocol.https.HttpsClient.New(Unknown Source)
at sun.net.www.protocol.https.AbstractDelegateHttpsURLConnection.getNewHttpClient(Unknown Source)
at sun.net.www.protocol.http.HttpURLConnection.plainConnect(Unknown Source)
at sun.net.www.protocol.https.AbstractDelegateHttpsURLConnection.connect(Unknown Source)
at sun.net.www.protocol.http.HttpURLConnection.followRedirect(Unknown Source)
at sun.net.www.protocol.http.HttpURLConnection.getInputStream(Unknown Source)
at java.net.HttpURLConnection.getResponseCode(Unknown Source)
at sun.net.www.protocol.https.HttpsURLConnectionImpl.getResponseCode(Unknown Source)
at HttpIberdrola.sendPost(HttpIberdrola.java:91)
at HttpIberdrola.main(HttpIberdrola.java:54)  

,代码是:

    public class HttpIberdrola {

    private List<String> cookies;
    private HttpsURLConnection conn;

    private final String USER_AGENT = "Mozilla/5.0";

    public static void main(String[] args) throws Exception {


ServerSocket sk = new ServerSocket(80);  
Socket cliente = sk.accept();
    BufferedReader entrada = new BufferedReader(new    InputStreamReader(cliente.getInputStream()));
    PrintWriter salida = new PrintWriter(new OutputStreamWriter(cliente.getOutputStream()),true);
    String datos = entrada.readLine(); //RECIBE ENVÍO CONEXION DEL CLIENTE
    salida.println(datos); //ENVIA CONFIRMACION CONEXION A CLIENTE
    cliente.close();


String url = "https://www.iberdrola.es/clientes/index";
String iberdrola = "https://www.iberdrola.es/02sica/clientesovc/iberdrola?IDPAG=ESOVC_CONTRATOS_LCE";

HttpIberdrola http = new HttpIberdrola();

// make sure cookies is turn on
CookieHandler.setDefault(new CookieManager());

// 1. Send a "GET" request, so that you can extract the form's data.
String page = http.GetPageContent(url);
String postParams = http.getFormParams(page, "USER", "PASS");

// 2. Construct above post's content and then send a POST request for
// authentication
http.sendPost(url, postParams);

// 3. success then go to gmail.
String result = http.GetPageContent(iberdrola);
System.out.println(result);
    }

    private void sendPost(String url, String postParams) throws Exception {

URL obj = new URL(url);
conn = (HttpsURLConnection) obj.openConnection();

// Acts like a browser
conn.setUseCaches(false);
conn.setRequestMethod("POST");
conn.setRequestProperty("Host", "www.iberdrola.es");
conn.setRequestProperty("User-Agent", USER_AGENT);
conn.setRequestProperty("Accept",
    "text/html,application/xhtml+xml,application/xml;q=0.9,*/*;q=0.8");
conn.setRequestProperty("Accept-Language", "es-ES,es;q=0.8");
for (String cookie : this.cookies) {
    conn.addRequestProperty("Cookie", cookie.split(";", 1)[0]);
}
conn.setRequestProperty("Connection", "keep-alive");
conn.setRequestProperty("Referer", "https://www.iberdrola.es/02sica/ngc/es/util/desconectar.jsp");
conn.setRequestProperty("Content-Type", "text/html;charset=ISO-8859-1");
conn.setRequestProperty("Content-Length", Integer.toString(postParams.length()));

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

// Send post request
DataOutputStream wr = new DataOutputStream(conn.getOutputStream());
wr.writeBytes(postParams);
wr.flush();
wr.close();

int responseCode = conn.getResponseCode();
System.out.println("\nSending 'POST' request to URL : " + url);
System.out.println("Post parameters : " + postParams);
System.out.println("Response Code : " + responseCode);

BufferedReader in = 
         new BufferedReader(new InputStreamReader(conn.getInputStream()));
String inputLine;
StringBuffer response = new StringBuffer();

while ((inputLine = in.readLine()) != null) {
    response.append(inputLine);
}
in.close();
//System.out.println(response.toString());

    }

    private String GetPageContent(String url) throws Exception {

URL obj = new URL(url);
conn = (HttpsURLConnection) obj.openConnection();

// default is GET
conn.setRequestMethod("GET");

conn.setUseCaches(false);

// act like a browser
conn.setRequestProperty("User-Agent", USER_AGENT);
conn.setRequestProperty("Accept",
    "text/html,application/xhtml+xml,application/xml;q=0.9,*/*;q=0.8");
conn.setRequestProperty("Accept-Language", "es-ES,es;q=0.8");
if (cookies != null) {
    for (String cookie : this.cookies) {
        conn.addRequestProperty("Cookie", cookie.split(";", 1)[0]);
    }
}
int responseCode = conn.getResponseCode();
System.out.println("\nSending 'GET' request to URL : " + url);
System.out.println("Response Code : " + responseCode);

BufferedReader in = 
        new BufferedReader(new InputStreamReader(conn.getInputStream()));
String inputLine;
StringBuffer response = new StringBuffer();

while ((inputLine = in.readLine()) != null) {
    response.append(inputLine);
}
in.close();

// Get the response cookies
setCookies(conn.getHeaderFields().get("Set-Cookie"));

return response.toString();

    }

    public String getFormParams(String html, String username, String password)
    throws UnsupportedEncodingException {

System.out.println("Extracting form's data...");

Document doc = Jsoup.parse(html);

// Iberdrola form id
Element loginform = doc.getElementById("login");
Elements inputElements = loginform.getElementsByTag("input");
List<String> paramList = new ArrayList<String>();
for (Element inputElement : inputElements) {
    String key = inputElement.attr("name");
    String value = inputElement.attr("value");

    if (key.equals("alias"))
        value = username;
    else if (key.equals("clave"))
        value = password;
    paramList.add(key + "=" + URLEncoder.encode(value, "UTF-8"));
}

// build parameters list
StringBuilder result = new StringBuilder();
for (String param : paramList) {
    if (result.length() == 0) {
        result.append(param);
    } else {
        result.append("&" + param);
    }
}

return result.toString();
    }

我已经阅读了其他类似问题的帖子(代理,防火墙......)但我找不到问题的答案。我已尝试使用Google电子邮件的登录帐户和他的“身份表单”页面的相同示例,并且工作完美。我已经禁用了Windows 7防火墙。我可以ping www.google.com(接收套餐),但不能ping www.iberdrola.es(所有包丢失)。

我认为问题在于iberdrola主机受到保护,我感到困惑吗?问题是我需要(必须)获取此页面上的数据并访问它。我能做些什么来解决这个问题?

提前致谢

1 个答案:

答案 0 :(得分:0)

DNS中未定义主机名larrun.iberdrola.es。该主机名不存在。

www.iberdrola.es存在且可在端口80(WWW)上访问。主机是否响应ping将取决于主机和/或域的防火墙的配置方式。有些主机响应ping,有些则没有。缺乏对ping的响应并不意味着无法通过TCP访问主机。

但是,在您的情况下,您提供的主机名不存在。您需要找出正确的主机名并替换它。