以下代码段演示了如何使用 HttpURLConnection 执行更高级的请求,并通过 PUT 请求从网络表单提交数据:
URLurl=newURL("http://jsonplaceholder.typicode.com/posts/"+id);HttpURLConnectionconn=(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.JSONObjectjsonObj=newJSONObject().put("userId",1).put("id",id).put("title",text).put("body",text);OutputStreamWriterwriter=newOutputStreamWriter(conn.getOutputStream());writer.write(jsonObj.toString());writer.close();intrespCode=conn.getResponseCode();// New items get NOT_FOUND on PUTif(respCode==HttpURLConnection.HTTP_OK||respCode==HttpURLConnection.HTTP_NOT_FOUND){req.setAttribute("error","");StringBuilderresponse=newStringBuilder();Stringline;// Read input data stream.BufferedReaderreader=newBufferedReader(newInputStreamReader(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());}
[[["易于理解","easyToUnderstand","thumb-up"],["解决了我的问题","solvedMyProblem","thumb-up"],["其他","otherUp","thumb-up"]],[["很难理解","hardToUnderstand","thumb-down"],["信息或示例代码不正确","incorrectInformationOrSampleCode","thumb-down"],["没有我需要的信息/示例","missingTheInformationSamplesINeed","thumb-down"],["翻译问题","translationIssue","thumb-down"],["其他","otherDown","thumb-down"]],["最后更新时间 (UTC):2025-09-04。"],[[["\u003cp\u003eThe \u003ccode\u003eREGION_ID\u003c/code\u003e is a Google-assigned code based on the region selected during app creation, included in App Engine URLs for apps created after February 2020, but it does not directly correspond to specific countries or provinces.\u003c/p\u003e\n"],["\u003cp\u003eJava 8 runtime applications utilize standard Java classes like \u003ccode\u003ejava.net.HttpURLConnection\u003c/code\u003e for HTTP(S) requests, which require billing to be enabled to avoid exceptions.\u003c/p\u003e\n"],["\u003cp\u003eWhile standard Java network classes provide benefits like removing the 32 MB limit and support for HTTP 2.0, avoid URL Fetch if using Serverless VPC Access or Cloud Client Libraries for Java, and ensure the \u003ccode\u003eurl-stream-handler\u003c/code\u003e is not set to \u003ccode\u003eurlfetch\u003c/code\u003e.\u003c/p\u003e\n"],["\u003cp\u003eYou can issue HTTP requests using \u003ccode\u003ejava.net.URLConnection\u003c/code\u003e, with more complex requests requiring \u003ccode\u003ejava.net.HttpURLConnection\u003c/code\u003e where you will need to create a \u003ccode\u003eURL\u003c/code\u003e object and set request method for the \u003ccode\u003eHttpURLConnection\u003c/code\u003e object.\u003c/p\u003e\n"],["\u003cp\u003eTo enhance security, disabling HTTP redirects with \u003ccode\u003econn.setInstanceFollowRedirects(false)\u003c/code\u003e is recommended, and when sending requests to another App Engine app, your app must include the \u003ccode\u003eX-Appengine-Inbound-Appid\u003c/code\u003e header.\u003c/p\u003e\n"]]],[],null,["# Issuing HTTP(S) Requests\n\n### Region ID\n\nThe \u003cvar translate=\"no\"\u003eREGION_ID\u003c/var\u003e is an abbreviated code that Google assigns\nbased on the region you select when you create your app. The code does not\ncorrespond to a country or province, even though some region IDs may appear\nsimilar to commonly used country and province codes. For apps created after\nFebruary 2020, \u003cvar translate=\"no\"\u003eREGION_ID\u003c/var\u003e`.r` is included in\nApp Engine URLs. For existing apps created before this date, the\nregion ID is optional in the URL.\n\nLearn more\n[about region IDs](/appengine/docs/legacy/standard/java/how-requests-are-routed#region-id). \nOK\n\nThis page describes how to issue HTTP(S) requests from your App Engine\napp.\nBy 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:\n\n\u003cbr /\u003e\n\n- `java.net.UnknownHostException`\n- `java.net.SocketTimeoutException`\n- `java.io.IOException`\n\nUsing standard runtime network classes\n--------------------------------------\n\nIf you use the standard Java network classes, your app will have access to the\nfollowing features:\n\n- The 32 MB limit on request data is removed.\n- Support for HTTP 2.0.\n- Supports all Google Cloud-based APIs accessible from the [Google Cloud Client Library for Java](https://cloud.google.com/java/docs/reference).\n\n### Using URL Fetch\n\n| **Warning:** Don't use URL Fetch if you have [set up Serverless VPC Access](/appengine/docs/legacy/standard/java/connecting-vpc) or use [Cloud Client Libraries for Java](https://github.com/googleapis/google-cloud-java). URL Fetch will handle all outbound requests and cause requests that you send to your VPC network or the client libraries to fail. If any of these scenarios apply to you, make sure that the `url-stream-handler` field in your configuration is not set to `urlfetch`. Apps that use Cloud Client Libraries for Java and attempt to use URL Fetch through the `URLConnection` wrapper are not supported.\n\nIf you have to use URL Fetch in a Java 8 app, add the following line to your\n[appengine-web.xml](/appengine/docs/legacy/standard/java/config/appref#url-stream-handler): \n\n \u003curl-stream-handler\u003eurlfetch\u003c/url-stream-handler\u003e\n\nFor example: \n\n \u003cxml version=\"1.0\" encoding=\"utf-8\"\u003e\n \u003cappengine-web-app xmlns=\"http://appengine.google.com/ns/1.0\"\u003e\n \u003c!-- ... --\u003e\n \u003curl-stream-handler\u003eurlfetch\u003c/url-stream-handler\u003e\n \u003c!-- ... --\u003e\n \u003c/appengine-web-app\u003e\n\n| **Note:** The metadata server can only be accessed using native Java sockets and the native stream handler and does not support the `urlfetch` service.\n\nIssue an HTTP request\n---------------------\n\nYou issue an outbound HTTP request using [`java.net.URLConnection`](https://docs.oracle.com/javase/7/docs/api/java/net/URLConnection.html).\n\n\u003cbr /\u003e\n\nThe following snippet demonstrates how to perform a basic HTTP `GET` request.\nThe application creates a new `URL` object, then calls the object's\n`openStream()` method to retrieve the content at that URL: \n\n URL url = new URL(\"http://api.icndb.com/jokes/random\");\n BufferedReader reader = new BufferedReader(new InputStreamReader(url.openStream()));\n StringBuffer json = new StringBuffer();\n String line;\n\n while ((line = reader.readLine()) != null) {\n json.append(line);\n }\n reader.close();\n\nFor more advanced requests, use `java.net.HttpURLConnection` as follows:\n\n1. Create a new `URL` object.\n2. Create a new `URLConnection` object by calling your `URL` object's `openConnection()` method.\n3. Create a new `HttpURLConnection` object by casting your `URLConnection` object to the `HttpURLConnection` object type.\n4. Set the `HttpURLConnection` object's request method.\n5. Create an output stream for the request.\n6. Write the request payload to the stream.\n7. Close the stream.\n\nThe following snippet demonstrates how to use `HttpURLConnection` to\nperform a more advanced request, submitting data from a web form via\na `PUT` request: \n\n URL url = new URL(\"http://jsonplaceholder.typicode.com/posts/\" + id);\n HttpURLConnection conn = (HttpURLConnection) url.openConnection();\n // Enable output for the connection.\n conn.setDoOutput(true);\n conn.setRequestProperty(\"Content-Type\", \"application/json; charset=UTF-8\");\n conn.setRequestProperty(\"Accept\", \"application/json\");\n // Set HTTP request method.\n conn.setRequestMethod(\"PUT\");\n\n // Create JSON request.\n JSONObject jsonObj =\n new JSONObject().put(\"userId\", 1).put(\"id\", id).put(\"title\", text).put(\"body\", text);\n\n OutputStreamWriter writer = new OutputStreamWriter(conn.getOutputStream());\n writer.write(jsonObj.toString());\n writer.close();\n\n int respCode = conn.getResponseCode(); // New items get NOT_FOUND on PUT\n if (respCode == HttpURLConnection.HTTP_OK || respCode == HttpURLConnection.HTTP_NOT_FOUND) {\n req.setAttribute(\"error\", \"\");\n StringBuilder response = new StringBuilder();\n String line;\n\n // Read input data stream.\n BufferedReader reader = new BufferedReader(new InputStreamReader(conn.getInputStream()));\n while ((line = reader.readLine()) != null) {\n response.append(line);\n }\n reader.close();\n req.setAttribute(\"response\", response.toString());\n } else {\n req.setAttribute(\"error\", conn.getResponseCode() + \" \" + conn.getResponseMessage());\n }\n\n### Set a request timeout\n\nIf you are using URL Fetch, you can adjust the default deadline for\nrequests [using the appengine.api.urlfetch.defaultDeadline](/appengine/docs/legacy/standard/java/config/appref#urlfetch_timeout)\nsetting in the `appengine-web.xml` file.\n\n### Set headers\n\nIf you are using URL Fetch, you can set an HTTP header on the outgoing request,\nby calling your `HttpURLConnection` object's `setRequestProperty()` method. The\nfollowing snippet sets the `X-MyApp-Version` header to `2.7.3`: \n\n conn.setRequestProperty(\"X-MyApp-Version\", \"2.7.3\");\n\n### Disable redirects\n\n| **Important:** To improve the security of your app, it is recommended that you disable redirects.\nBy default, `HttpURLConnection` follows HTTP redirects.\n\nIf you are using URL Fetch, the underlying URL Fetch service follows up to five\nredirects by default. These redirects could forward sensitive information, such\nas authorization headers, to the redirected destination. If your app does not\nrequire HTTP redirects, it is recommended that you disable the redirects.\n\nTo disable this behavior, pass the value `false` to your `HttpURLConnection`\nobject's `setInstanceFollowRedirects()` method: \n\n conn.setInstanceFollowRedirects(false);\n\nIf your app uses the underlying `urlfetch` package directly\ninstead of `java.net`, your app must specify\n[`doNotFollowRedirects`](/appengine/docs/legacy/standard/java/javadoc/com/google/appengine/api/urlfetch/FetchOptions).\n\nIssue an HTTPS request\n----------------------\n\nBy default, the underlying URL Fetch service validates the certificate\nof the host it contacts, and rejects requests if the certificate\ndoesn't match. You don't need to explicitly secure your request.\n\n### Disable host certificate validation\n\nTo disable automatic host certificate validation in URL Fetch,\nissue an HTTPS request using the `FetchOptions`\nclass in the `urlfetch` package and call `doNotValidateCertificate()`.\n\nIssue an asynchronous request\n-----------------------------\n\nHTTP(S) requests are synchronous by default. To issue an asynchronous\nrequest, your application must use\n[`URLFetchService`'s](/appengine/docs/legacy/standard/java/javadoc/com/google/appengine/api/urlfetch/URLFetchService)\n`fetchAsync()` method. This method returns a\n`java.util.concurrent.Future\u003cHTTPResponse\u003e`.\n\nIssue a request to another App Engine app\n-----------------------------------------\n\nWhen issuing a request to another App Engine app, your App Engine app\nmust assert its identity by adding the header `X-Appengine-Inbound-Appid`\nto the request.\nIf you instruct the URL Fetch service to not follow redirects, App Engine\nwill add this header to requests automatically.\n\nSee [Disabling redirects](#disabling_redirects) for guidance on disabling\nredirects.\n| **Note:** If you are making requests to another App Engine application, use its \u003cvar translate=\"no\"\u003e\u003ca href=\"#appengine-urls\" style=\"border-bottom: 1px dotted #999\" class=\"devsite-dialog-button\" data-modal-dialog-id=\"regional_url\" track-type=\"progressiveHelp\" track-name=\"modalHelp\" track-metadata-goal=\"regionalURL\"\u003eREGION_ID\u003c/a\u003e\u003c/var\u003e`.r.appspot.com` domain name rather than a custom domain for your app.\n\nWhat's next\n-----------\n\nLearn about the URL Fetch service, such as the headers that are\nsent in a URL Fetch request in [Outbound Requests](/appengine/docs/legacy/standard/java/outbound-requests)."]]