我不知道如何使用这个API来获取index.html
请给我看一个示例。
这是我的完整代码,HTTP 错误 500
package com.webrt;
import java.io.IOException;
import javax.servlet.http.*;
import com.google.api.client.extensions.appengine.http.UrlFetchTransport;
import com.google.api.client.http.GenericUrl;
import com.google.api.client.http.HttpRequest;
import com.google.api.client.http.HttpRequestFactory;
@SuppressWarnings("serial")
public class WebRTServlet extends HttpServlet {
public void doGet(HttpServletRequest req, HttpServletResponse resp)
throws IOException {
resp.setContentType("text/plain");
UrlFetchTransport HTTP_TRANSPORT = new UrlFetchTransport();
HttpRequestFactory httprequestFactory = HTTP_TRANSPORT
.createRequestFactory();
GenericUrl url = new GenericUrl("http://www.google.com");
HttpRequest request = httprequestFactory.buildGetRequest(url);
String index = request.execute().parseAsString();
System.out.println(index);
}
}
最佳答案
您可以找到samples here以及有关图书馆的信息here 。要使用该库获取文件,只需对该文件发出 get 请求即可。 index.html
页面也不异常(exception)。
这是一个基本示例:
您使用的 HTTP 传输在此上下文中并不重要。 UrlFetchTransport
对于 AppEngine 应用程序很有用,但它只是进行 HTTP 调用的方式。无论您将常量 HTTP_TRANSPORT
设置为哪种传输(UrlFetch、NetHttp 等),以下代码都应该有效。
HttpRequestFactory requestFactory = HTTP_TRANSPORT.createRequestFactory();
GenericUrl url = new GenericUrl("http://example.iana.org/index.html");
HttpRequest request = requestFactory.buildGetRequest(url);
String index = request.execute().parseAsString();
从这里您可以将index
保存到文件、打印它或任何您想要的内容。这将是浏览器看到的完整文件。
关于java - 如何使用 com.google.api.client.extensions.appengine.http.UrlFetchTransport 获取 index.html,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/16521100/