首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >使用Eclipse中的openConnection()实现UnknownHostException和未知源代码

问使用Eclipse中的openConnection()实现UnknownHostException和未知源代码
EN

Stack Overflow用户
提问于 2013-09-30 23:46:23
回答 1查看 7.2K关注 0票数 0

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

我在Eclipse工具中有一个java项目。实际上,它是一个java服务器,它必须在web中解析数据,并且在同一web中模拟登录后才能解析数据。我用android手机(客户端)激活了这个服务器,它会发送消息(典型的客户端-服务器应用程序)。所有这些都是通过本地wifi连接完成的。问题是:

代码语言:javascript
复制
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)  

代码是:

代码语言:javascript
复制
    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();
    }

我读过其他有类似问题的帖子(代理,防火墙,...)但是我没有找到我的问题的答案。我用谷歌电子邮件的登录帐户和他的"id表单“页面尝试了同样的例子,效果很好。我已经禁用了windows7防火墙。我可以做ping www.google.com (接收包),但不能做ping www.iberdrola.es (所有包丢失)。

我认为问题是iberdrola主机是受保护的,我是不是很困惑?问题是,我需要(强制性的)获取这个页面上的数据并访问它。我能做些什么来解决这个问题?

提前感谢

EN

回答 1

Stack Overflow用户

发布于 2013-10-01 00:03:46

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

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

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

票数 0
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/19098437

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档