|
| 1 | +/* |
| 2 | + * Copyright 2019 Google LLC |
| 3 | + * |
| 4 | + * Licensed under the Apache License, Version 2.0 (the "License"); |
| 5 | + * you may not use this file except in compliance with the License. |
| 6 | + * You may obtain a copy of the License at |
| 7 | + * |
| 8 | + * http://www.apache.org/licenses/LICENSE-2.0 |
| 9 | + * |
| 10 | + * Unless required by applicable law or agreed to in writing, software |
| 11 | + * distributed under the License is distributed on an "AS IS" BASIS, |
| 12 | + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. |
| 13 | + * See the License for the specific language governing permissions and |
| 14 | + * limitations under the License. |
| 15 | + */ |
| 16 | + |
| 17 | +// [START functions_http_content] |
| 18 | + |
| 19 | +import com.google.gson.Gson; |
| 20 | +import com.google.gson.JsonObject; |
| 21 | +import java.io.IOException; |
| 22 | +import java.io.PrintWriter; |
| 23 | +import java.util.Base64; |
| 24 | +import javax.servlet.http.HttpServletRequest; |
| 25 | +import javax.servlet.http.HttpServletResponse; |
| 26 | + |
| 27 | +public class ParseContentType { |
| 28 | + |
| 29 | + // Use GSON (https://github.com/google/gson) to parse JSON content. |
| 30 | + private Gson gsonParser = new Gson(); |
| 31 | + |
| 32 | + // Responds to an HTTP request using data from the request body parsed according to the |
| 33 | + // "content-type" header. |
| 34 | + public void parseContentType(HttpServletRequest request, HttpServletResponse response) |
| 35 | + throws IOException { |
| 36 | + String name; |
| 37 | + String contentType = request.getContentType(); |
| 38 | + if (contentType.equals("application/json")) { |
| 39 | + // '{"name":"John"}' |
| 40 | + JsonObject body = gsonParser.fromJson(request.getReader(), JsonObject.class); |
| 41 | + name = body.get("name").getAsString(); |
| 42 | + } else if (contentType.equals("application/octet-stream")) { |
| 43 | + // 'John', stored in a Buffer |
| 44 | + name = new String(Base64.getDecoder().decode(request.getInputStream().readAllBytes())); |
| 45 | + } else if (contentType.equals("text/plain")) { |
| 46 | + // 'John' |
| 47 | + name = request.getReader().readLine(); |
| 48 | + } else if (contentType.equals("application/x-www-form-urlencoded")) { |
| 49 | + // 'name=John' in the body of a POST request (not the URL) |
| 50 | + name = request.getParameter("name"); |
| 51 | + } else { |
| 52 | + // Invalid or missing header "Content-Type" |
| 53 | + response.setStatus(HttpServletResponse.SC_BAD_REQUEST); |
| 54 | + return; |
| 55 | + } |
| 56 | + PrintWriter writer = response.getWriter(); |
| 57 | + writer.write(String.format("Hello %s!", name)); |
| 58 | + } |
| 59 | +} |
| 60 | + |
| 61 | +// [END functions_http_content] |
0 commit comments