java access to weather forecasts

2010-07-24  来源:本站原创  分类:Java  人气:179 

Recent projects use to weather, I had been provided had heard webservice applications on the network, so you can call interface is very simple to get data. But in fact when I do, but very depressing. In the beginning, I have not found time since the beginning of a very smooth, and then run the project on the server when the weather is a problem with this piece, after investigation, the original is to provide a certain amount of people per day visit volume, than not to the data. I think quite to gas, this is not a waste of my time Well. Later, at a lot, unsuccessful.

Finally, I would rather use google it, the following program theory, submit a request to google, and then parsing the page.

The program:

Java code
package mobi.tuitui.util;

import java.io.IOException;
import java.net.URLEncoder;
import java.util.Date;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

import org.apache.commons.httpclient.DefaultHttpMethodRetryHandler;
import org.apache.commons.httpclient.HttpClient;
import org.apache.commons.httpclient.HttpException;
import org.apache.commons.httpclient.HttpStatus;
import org.apache.commons.httpclient.methods.GetMethod;
import org.apache.commons.httpclient.params.HttpMethodParams;

public class WeatherReport (

/ **
* Send a request to obtain the weather information pages GOOGLE
* @ Param city
* @ Return
* @ Throws Exception
* /
@ SuppressWarnings ("deprecation")
private static String getInputStream (String city) (
try (
HttpClient httpClient = new HttpClient ();
String hostUrl = "http://www.google.cn/search?hl=zh-CN&q=tq% 20" + URLEncoder.encode (city);
GetMethod getMethod = new GetMethod (hostUrl);
/ / Use system default recovery strategy
getMethod.getParams (). setParameter (HttpMethodParams.RETRY_HANDLER, new DefaultHttpMethodRetryHandler ());
try (
/ / Execute getMethod
int statusCode = httpClient.executeMethod (getMethod);
if (statusCode! = HttpStatus.SC_OK) (
System.err.println ("Method failed:" + getMethod.getStatusLine ());
)
String result = getMethod.getResponseBodyAsString ();
return result;
) Catch (HttpException e) (
/ / Fatal exception, possibly return to the contents of the agreement or not a problem
System.out.println ("Please check your provided http address!");
e.printStackTrace ();
) Catch (IOException e) (
/ / Exception occurred Network
e.printStackTrace ();
) Finally (
/ / Release connections
getMethod.releaseConnection ();
)
) Catch (Exception e) (
e.printStackTrace ();
return null;
)
return null;
)

/ **
* Weather page to get the information that contains the relevant weather information analysis
* @ Param result
* @ Identifier
* @ Return
* /
public static String readText (String result, String identifier) (
Pattern shopNumberPattern = Pattern.compile (identifier);
Matcher shopNamMatcher = shopNumberPattern.matcher (result);
if (shopNamMatcher.find ())
return shopNamMatcher.group (1);
return "";
)

public static String getWeather (String city) (
String result = readText (getInputStream (city), "<div\"padding:5px;float:left\"> (.+?)</ div> </ div>");
String weatherDetail = readText (result, "<div\"font-size:140%\"> (.+?)%");
weatherDetail = weatherDetail.replaceAll ("<div>", ""). replaceAll ("</ div>", ""). replaceAll ("<br>", ""). replace (":", ":" );
return weatherDetail;
)

)
package mobi.tuitui.util;

import java.io.IOException;
import java.net.URLEncoder;
import java.util.Date;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

import org.apache.commons.httpclient.DefaultHttpMethodRetryHandler;
import org.apache.commons.httpclient.HttpClient;
import org.apache.commons.httpclient.HttpException;
import org.apache.commons.httpclient.HttpStatus;
import org.apache.commons.httpclient.methods.GetMethod;
import org.apache.commons.httpclient.params.HttpMethodParams;

public class WeatherReport (

/ **
* Send a request to obtain the weather information pages GOOGLE
* @ Param city
* @ Return
* @ Throws Exception
* /
@ SuppressWarnings ("deprecation")
private static String getInputStream (String city) (
try (
HttpClient httpClient = new HttpClient ();
String hostUrl = "http://www.google.cn/search?hl=zh-CN&q=tq% 20" + URLEncoder.encode (city);
GetMethod getMethod = new GetMethod (hostUrl);
/ / Use system default recovery strategy
getMethod.getParams (). setParameter (HttpMethodParams.RETRY_HANDLER, new DefaultHttpMethodRetryHandler ());
try (
/ / Execute getMethod
int statusCode = httpClient.executeMethod (getMethod);
if (statusCode! = HttpStatus.SC_OK) (
System.err.println ("Method failed:" + getMethod.getStatusLine ());
)
String result = getMethod.getResponseBodyAsString ();
return result;
) Catch (HttpException e) (
/ / Fatal exception, possibly return to the contents of the agreement or not a problem
System.out.println ("Please check your provided http address!");
e.printStackTrace ();
) Catch (IOException e) (
/ / Exception occurred Network
e.printStackTrace ();
) Finally (
/ / Release connections
getMethod.releaseConnection ();
)
) Catch (Exception e) (
e.printStackTrace ();
return null;
)
return null;
)

/ **
* Weather page to get the information that contains the relevant weather information analysis
* @ Param result
* @ Identifier
* @ Return
* /
public static String readText (String result, String identifier) (
Pattern shopNumberPattern = Pattern.compile (identifier);
Matcher shopNamMatcher = shopNumberPattern.matcher (result);
if (shopNamMatcher.find ())
return shopNamMatcher.group (1);
return "";
)

public static String getWeather (String city) (
String result = readText (getInputStream (city), "<div\"padding:5px;float:left\"> (.+?)</ div> </ div>");
String weatherDetail = readText (result, "<div\"font-size:140%\"> (.+?)%");
weatherDetail = weatherDetail.replaceAll ("<div>", ""). replaceAll ("</ div>", ""). replaceAll ("<br>", ""). replace (":", ":" );
return weatherDetail;
)

)

Procedures used httpClient. Version seems to be 1.3. I am here just the weather today, in fact, google offers a few days, you can go based on demand analysis page.

On the weather, his best write cache, the cache of each city in which the weather every day, if the next user is the same city, then on the speed of response to events. My approach to the current date with the weather into a class, then the city as a map of the key, the class object as a map of the value. Access to the first map with the city to look for, if the date object will hit out compared with the current date, if it is today, then returned directly.

相关文章
  • java access to weather forecasts 2010-07-24

    Recent projects use to weather, I had been provided had heard webservice applications on the network, so you can call interface is very simple to get data. But in fact when I do, but very depressing. In the beginning, I have not found time since the

  • java access to weather forecast 2009-01-24

    Recent projects use the weather forecast, I had always heard that the network is provided webservice applications, so you can call interface is very simple to get the data. But the fact that I do it, but it is very depressed. At the beginning of time

  • Weather forecasts based on google's weatherAPI 2010-07-10

    General access to weather information in two ways 1, called third-party api, to obtain necessary information 2, capture web content, by regular expression matching to obtain needed information Of course, you also can find the relevant units of the Ce

  • java access to the LDAP mode 2010-08-03

    1. JNDI (JAVA Naming and Directory Interface) JNDI is a JAVA Naming and Directory Service Access for the development of standards based interfaces for access, including DNS, NIS, LDAP, file system directory tree form any target, and can basically be

  • java access to the shared directory (samba and NFS configuration and implementation) 2010-10-28

    Recently required under linux using java to access the shared directory for file downloads and uploads, as linux mainly two ways to share files, samba and NFS, samba is based on Microsoft's smb / cifs protocol, NFS Network File System (Network File S

  • Java access modifiers 2011-04-19

    In the Java language has 4 access modifiers: package (default), private, public and protected. 1. package is the default protection mode, again and again to do packet access, no modifier when using this protection mode. Package access allows fields a

  • JAVA access firebird database of Jaybird 2011-01-02

    JAVA access firebird database of Jaybird About Jaybird-2.1.6JDK_1.5 use as follows: First: Install Jaybird The first step: the root directory jaybird21.dll, GDS32.DLL, icudt30.dll, icuuc30.dll, fbembed.dll, icuin30.dll fbclient.dll (FB type for non-e

  • java access modifiers public protected friendly private usage summary 2009-04-01

    First, the statement: java in, friendly, and this modifier is not an explicit statement of the member variables and methods of the former would not have any modifiers, the default is friendly. For clarity, sub-summed up in three different circumstanc

  • Java access to system information (cpu, memory, hard disk, process, etc.) Related to methods 2010-04-04

    1. Jdk that comes with using API to obtain information: (the above version only supports jdk1.60 ah) import java.io.InputStreamReader; import java.io.LineNumberReader; import java.util.ArrayList; import java.util.List; import mytools.com.sun.manageme

  • Base entry: Java access to URL resources corresponding 2010-07-02

    Understanding of IP, understanding of network programming URL is the first step. java.net.URL URL provides a way to build wealth, and to obtain resources through the java.net.URL. First, understand URL Class URL represents a Uniform Resource Locator,

  • java access to operating system information through the JVM 2010-09-09

    import java.util.Enumeration; import java.util.Hashtable; import java.util.Properties; public class TestJVMGetSystemInfo ( / / Store received JVM System Properties static private Properties _property; / / Main function public static void main (String

  • JAVA access to MySQL database issues 2010-12-30

    In fact, said before JAVA code to access the database, here again explain the problem to access MySQL. Limited resources under the Windows XP VM build a Unbuntu using the Linux system, more scary is loaded three times in the same way, except that thi

  • Reply: Java access to generic type 2010-03-29

    Switched from Java to obtain the generic type of response, content of fine-tuning. Java generics have such a law: Located at the side of the statement, the source where what is written to the run-time will be able to see that; In the use of one side,

  • Java access to the machine ip and host name 2008-08-16

    Idle today, all right, Internet search a bit how to get Java native ip and host name. Mainly used in the java.net package under the InetAddress class, this class is the abstract of the ip address. Procedures are as follows: import java.net.InetAddres

  • java access to the network image 2009-12-22

    package com.yss.test.FileReadWriter; import java.awt.AWTEvent; import java.awt.Frame; import java.awt.Graphics; import java.awt.Image; import java.awt.event.WindowEvent; import java.awt.image.ImageProducer; import java.io.IOException; import java.net

  • java access to the current system memory and hard disk usage 2010-03-24

    Wrote import java.lang.management.ManagementFactory; import com.sun.management.OperatingSystemMXBean; public class Test ( public static void main (String [] args) ( OperatingSystemMXBean osmb = (OperatingSystemMXBean) ManagementFactory.getOperatingSy

  • Java access to database information (simple) 2010-03-30

    When you use the JDK and learning, they can see and learn what it offers you two ResultSetMetaData And DataBaseMetaData class source code and to achieve a good understanding of their principles and ideas, JDBC provides two sources of data, one is the

  • Weather forecasts based on Htmlparser program (continued) 2010-04-13

    Combined with a search online to find the ip of the webservice get the machine where the city, get the weather that day. In the laboratory discovered a small problem is that some students of the computer program running in the dynamic, some students

  • Java access to the machine IP 2010-04-27

    I started using Linux, InetAddress.getLocalHost () method to get the machine IP address, The results obtained is always: 127.0.1.1. This is the original etc / hosts file configuration, not the network card's IP address. Later, multi-search, and final

  • Java access to the current system time 2010-04-28

    // Import import java.util.Date; import java.text.DateFormat; import java.text.SimpleDateFormat; Date dt=new Date();// If you do not need to format, can be directly used dt,dt Is the current system time DateFormat df = new SimpleDateFormat("yyyy/MM/d