なお、このサービスの使い方も簡単です。
このサンプルでは三つもURL取得方法を紹介します。
UrlfetchServlet.java
package urlfetch;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.net.HttpURLConnection;
import java.net.MalformedURLException;
import java.net.URL;
import javax.servlet.http.*;
import com.google.appengine.api.urlfetch.HTTPRequest;
import com.google.appengine.api.urlfetch.URLFetchServiceFactory;
@SuppressWarnings("serial")
public class UrlfetchServlet extends HttpServlet
{
public void doGet(HttpServletRequest req, HttpServletResponse resp)
throws IOException
{
String cmd = req.getParameter("cmd");
URL url = new URL("http://www.google.co.jp");
try
{
if (cmd.equals("1"))
{
resp.setCharacterEncoding("utf-8");
resp.setContentType("text/plain");
BufferedReader reader = new BufferedReader(
new InputStreamReader(url.openStream()));
String line;
while ((line = reader.readLine()) != null)
{
resp.getWriter().println(line);
}
reader.close();
} else if (cmd.equals("2"))
{
resp.setCharacterEncoding("shift-jis");
HttpURLConnection urlconn = (HttpURLConnection) url
.openConnection();
urlconn.setRequestProperty("use_intranet", "true");
urlconn.setConnectTimeout(10000);
BufferedReader reader = new BufferedReader(
new InputStreamReader(url.openStream()));
String line;
while ((line = reader.readLine()) != null)
{
resp.getWriter().println(line);
}
reader.close();
} else if (cmd.equals("3"))
{
resp.setCharacterEncoding("utf-8");
resp.setContentType("text/html");
String out = new String(URLFetchServiceFactory
.getURLFetchService().fetch(new HTTPRequest(url))
.getContent());
resp.getWriter().println(out);
}
} catch (MalformedURLException e)
{
resp.getWriter().println("URL指定エラー");
} catch (IOException e)
{
resp.getWriter().println("IOエラー");
}
}
}
0 件のコメント:
コメントを投稿