GAE-Google App Engine网址抓取(java.net.UrlConnection)

23 一月 2010 | J2EE | Tags: , , ,

Google App Engine 的网址抓取挺方便的,可以使用java.net.UrlConnection这个类。有了这个我们可以干什么?例如可以从某处获取天气信息等等~

(提醒一下,上面的是图片。。不要误点了啊。。。)
看看例子:http://2.latest.fatkuns.appspot.com/

GAE网址抓取是什么?

App Engine 应用程序可以抓取资源,并通过互联网使用 HTTP 和 HTTPS 请求与其他主机通信。应用程序使用网址抓取服务来进行请求。

我觉得其实就是可以通过它抓取别人网页的源代码。

使用URL获取源码

package com.fatkun;
/**
 * 在GAE上抓取网址
 * @author Fatkun
 * @site http://fatkun.com
 */
 
import java.io.IOException;
import java.io.InputStreamReader;
import java.net.URL;
 
import javax.servlet.http.*;
 
@SuppressWarnings("serial")
public class URL2Servlet extends HttpServlet {
	public void doGet(HttpServletRequest req, HttpServletResponse resp) throws IOException {
		resp.setContentType("text/plain; charset=utf-8");//显示编码
 
		URL url = new URL("http://fatkun.com");
		// 读取源码
		//读取中文时,使用Reader类是每次读出两个字节的,不会出现中文乱码
		InputStreamReader in = new InputStreamReader(url.openStream(), "UTF-8");
		char[] buf = new char[2048];//缓存
		StringBuffer sb = new StringBuffer();
		int len = 0;
		while ((len = in.read(buf)) != -1) {//当没到文档尽头继续读取
			sb.append(buf, 0, len);
		}
 
		// 输出在网页上
		resp.getWriter().println(sb.toString());
	}
}

使用HttpURLConnection 来POST内容

// 此处的地址请换成你的,在本地测试时可以填入http://localhost:8888/request.jsp
URL url = new URL("http://2.latest.fatkuns.appspot.com/request.jsp");
HttpURLConnection connection = (HttpURLConnection) url.openConnection();
connection.setDoOutput(true);// 使用 URL 连接进行输出
connection.setRequestMethod("POST");
// 取得输出流
OutputStreamWriter writer = new OutputStreamWriter(connection.getOutputStream());
// 用UTF-8编码,保证中文传递正常
String message = URLEncoder.encode("你好,I'm Fatkun!", "UTF-8");
// 写入发送的内容
writer.write("msg=" + message);
writer.close();

上面是主要的代码,看注释好了,都很清楚。

Google App Engine中文乱码问题

注意在读取中文的网页时,由于编码是使用UTF或者GBK,GB2312等编码,使用InputStream类不太方便,另外有可以出现错误。
试过使用InputStream类,然后用new String(bytes[],”utf-8″)来转换编码,不过出现一点问题,不知道是我不会用还是怎么的。
不过使用这样的写法就方便多了。
InputStreamReader in = new InputStreamReader(url.openStream(), “UTF-8″);
编码都不用转换了~指定它的编码就行。
注意这里要加上“UTF-8”,虽然不加在本地测试时没问题,不过上传到GAE上就不能显示中文了。
PS2:这里的UTF-8是代表你抓取网页的编码。如果你抓取的网页是gb2312的需要根据实质需求改变。

附上我做的例子:http://2.latest.fatkuns.appspot.com/
源码在这里:http://2.latest.fatkuns.appspot.com/source.rar,里面的lib目录下的我删除了,请自行添加。


14 Responses to “ GAE-Google App Engine网址抓取(java.net.UrlConnection) ”

  1. evlos says:

    天哪,不会被墙了吧??!!例子打不开喔 ~

    • fatkun says:

      @evlos, 没有被墙~~只不过GAE有时打不开。。不知道是不是和天朝有关~~

      • 北街 says:

        @fatkun, 确实打不开!天草万岁! /汗

        • fatkun says:

          @北街, 额。。我居然可以打开。。。汗。。 /白眼

  2. /哟 这个是不是跟鱼鱼桌面秀里面的插件有点类似啊···

    • fatkun says:

      @AA牌熊仔饼, 没有了解过鱼鱼桌面秀插件耶~~
      这个是java语言写的~~

  3. diyidu says:

    不错,谢谢分享.

  4. alswl says:

    不错不错,Star and Share

  5. Ken says:

    想請問一下為什麼我在GAE裡面

    用兩個HttpURLConnection,第二個都不會成功?

    try {
    URL url_login = new URL(“http://www.plurk.com/API/Users/login”);
    URL url_add = new URL(“http://www.plurk.com/API/Timeline/plurkAdd”);
    HttpURLConnection conn_login = (HttpURLConnection) url_login.openConnection();
    HttpURLConnection conn_add;
    conn_login.setDoOutput(true);
    conn_login.setRequestMethod(“POST”);

    OutputStreamWriter writer = new OutputStreamWriter(conn_login.getOutputStream());
    writer.write(“xx=xx”);

    writer.close();
    conn_login.connect();
    if (conn_login.getResponseCode() == HttpURLConnection.HTTP_OK) {
    conn_login.disconnect();
    resp.getWriter().println(conn_login.getResponseCode());
    conn_add = (HttpURLConnection) url_add.openConnection();
    conn_add.setDoOutput(true);
    conn_add.setRequestMethod(“POST”);
    OutputStreamWriter writer_add = new OutputStreamWriter(conn_add.getOutputStream());
    writer_add.write(“xx=xx”);
    writer_add.close();

    resp.getWriter().println(conn_add.getResponseCode());
    } else {
    resp.getWriter().print(“fail”);
    }
    } catch (MalformedURLException e) {
    resp.getWriter().print(“fail”);
    } catch (IOException e) {
    resp.getWriter().print(“fail”);
    }

    • fatkun says:

      @Ken, 还没试过用两个呢,会不会是超时了被google强制返回?试试看看后台的记录。。

  6. 谢谢分享

  7. 我来看博主文章了,感谢分享哦!

  8. alswl says:

    被编码问题搞得很头疼
    存入数据库老出现问题,蛋疼

发表评论

电子邮件地址不会被公开。

您可以使用这些 HTML 标签和属性: <a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite> <code> <del datetime=""> <em> <i> <q cite=""> <strike> <strong> <pre lang="" line="" escaped="" highlight="">