Issuing HTTP(S) Requests

Region ID

The REGION_ID is a code that Google assigns based on the region you select when you create your app. Including REGION_ID.r in App Engine URLs is optional for existing apps and will soon be required for all new apps.

Learn more about region IDs.

This page describes how to issue HTTP(S) requests from your App Engine app.

By default, applications running in the Java 8 runtime use standard Java classes for HTTP(S) requests, such as java.net.HttpURLConnection.. You send requests as you would for any other Java application. To use the default behavior, you must enable billing for your application or you will get the following exceptions:

  • java.net.UnknownHostException
  • java.net.SocketTimeoutException
  • java.io.IOException

Using standard runtime network classes

If you use the standard Java network classes, your app will have access to the following features:

Using URLFetch

If you have to use URL Fetch in a Java 8 app, add the following line to your appengine-web.xml:

 <url-stream-handler>urlfetch</url-stream-handler>

For example:

<xml version="1.0" encoding="utf-8">
<appengine-web-app xmlns="http://appengine.google.com/ns/1.0">
  <!-- ... -->
  <url-stream-handler>urlfetch</url-stream-handler>
  <!-- ... -->
</appengine-web-app>

Notice that this setting does not require the app to be enabled for billing.

Issuing an HTTP request

You issue an outbound HTTP request using java.net.URLConnection.

The following snippet demonstrates how to perform a basic HTTP GET request. The application creates a new URL object, then calls the object's openStream() method to retrieve the content at that URL:

URL url = new URL("http://api.icndb.com/jokes/random");
BufferedReader reader = new BufferedReader(new InputStreamReader(url.openStream()));
StringBuffer json = new StringBuffer();
String line;

while ((line = reader.readLine()) != null) {
  json.append(line);
}
reader.close();

For more advanced requests, use java.net.HttpURLConnection as follows:

  1. Create a new URL object.
  2. Create a new URLConnection object by calling your URL object's openConnection() method.
  3. Create a new HttpURLConnection object by casting your URLConnection object to the HttpURLConnection object type.
  4. Set the HttpURLConnection object's request method.
  5. Create an output stream for the request.
  6. Write the request payload to the stream.
  7. Close the stream.

The following snippet demonstrates how to use HttpURLConnection to perform a more advanced request, submitting data from a web form via a PUT request:

URL url = new URL("http://jsonplaceholder.typicode.com/posts/" + id);
HttpURLConnection conn = (HttpURLConnection) url.openConnection();
// Enable output for the connection.
conn.setDoOutput(true);
conn.setRequestProperty("Content-Type", "application/json; charset=UTF-8");
conn.setRequestProperty("Accept", "application/json");
// Set HTTP request method.
conn.setRequestMethod("PUT");

// Create JSON request.
JSONObject jsonObj =
    new JSONObject().put("userId", 1).put("id", id).put("title", text).put("body", text);

OutputStreamWriter writer = new OutputStreamWriter(conn.getOutputStream());
writer.write(jsonObj.toString());
writer.close();

int respCode = conn.getResponseCode(); // New items get NOT_FOUND on PUT
if (respCode == HttpURLConnection.HTTP_OK || respCode == HttpURLConnection.HTTP_NOT_FOUND) {
  req.setAttribute("error", "");
  StringBuilder response = new StringBuilder();
  String line;

  // Read input data stream.
  BufferedReader reader = new BufferedReader(new InputStreamReader(conn.getInputStream()));
  while ((line = reader.readLine()) != null) {
    response.append(line);
  }
  reader.close();
  req.setAttribute("response", response.toString());
} else {
  req.setAttribute("error", conn.getResponseCode() + " " + conn.getResponseMessage());
}

Setting a request timeout

If you are using URL Fetch, you can adjust the default deadline for requests using the appengine.api.urlfetch.defaultDeadline setting in the appengine-web.xml file.

Setting headers

If you are using URL Fetch, you can set an HTTP header on the outgoing request, by calling your HttpURLConnection object's setRequestProperty() method. The following snippet sets the X-MyApp-Version header to 2.7.3:

conn.setRequestProperty("X-MyApp-Version", "2.7.3");

Disabling redirects

By default, HttpURLConnection follows HTTP redirects. If you are using URL Fetch, the underlying URL Fetch service will follow up to five redirects. To disable this behavior, pass the value false to your HttpURLConnection object's setInstanceFollowRedirects() method:

conn.setInstanceFollowRedirects(false);

If your app uses the underlying urlfetch package directly instead of java.net, your app must specify doNotFollowRedirects.

Issuing an HTTPS request

If you are using URL Fetch, issue an HTTPS request using the FetchOptions class in the urlfetch package and call validateCertificate().

Issuing an asynchronous request

HTTP(S) requests are synchronous by default. To issue an asynchronous request, your application must use URLFetchService's fetchAsync() method. This method returns a java.util.concurrent.Future<HTTPResponse>.

Issuing a request to another App Engine app

When issuing a request to another App Engine app, your App Engine app must assert its identity by adding the header X-Appengine-Inbound-Appid to the request. If you instruct the URL Fetch service to not follow redirects, App Engine will add this header to requests automatically. See Disabling redirects for guidance on disabling redirects.

What's next

Learn about the URL Fetch service, such as the headers that are sent in a URL Fetch request in Outbound Requests.

หน้านี้มีประโยชน์ไหม โปรดแสดงความคิดเห็น

ส่งความคิดเห็นเกี่ยวกับ...