Skip to content

Commit eafd2dc

Browse files
author
Les Vogel
committed
Add a more complex example as well.
1 parent db10bd9 commit eafd2dc

File tree

2 files changed

+109
-16
lines changed

2 files changed

+109
-16
lines changed

appengine/urlfetch/src/main/java/com/example/appengine/UrlFetchServlet.java

Lines changed: 61 additions & 16 deletions
Original file line numberDiff line numberDiff line change
@@ -18,40 +18,85 @@
1818

1919
import org.json.JSONObject;
2020

21-
import java.io.BufferedReader;
22-
import java.io.IOException;
23-
import java.io.InputStreamReader;
24-
import java.io.PrintWriter;
25-
import java.net.URL;
26-
21+
import javax.servlet.ServletException;
2722
import javax.servlet.http.HttpServlet;
2823
import javax.servlet.http.HttpServletRequest;
2924
import javax.servlet.http.HttpServletResponse;
25+
import java.io.*;
26+
import java.net.HttpURLConnection;
27+
import java.net.URL;
28+
import java.net.URLEncoder;
3029

3130
@SuppressWarnings("serial")
3231
public class UrlFetchServlet extends HttpServlet {
3332

3433
@Override
3534
public void doGet(HttpServletRequest req, HttpServletResponse resp)
36-
throws IOException {
37-
PrintWriter out = resp.getWriter();
38-
out.println("<html><body>");
35+
throws IOException, ServletException {
3936

4037
// [START example]
4138
URL url = new URL("http://api.icndb.com/jokes/random");
4239
BufferedReader reader = new BufferedReader(new InputStreamReader(url.openStream()));
43-
String json = "";
40+
StringBuffer json = new StringBuffer();
4441
String line;
4542

4643
while ((line = reader.readLine()) != null) {
47-
json += line;
44+
json.append(line);
4845
}
4946
reader.close();
5047
// [END example]
51-
JSONObject jo = new JSONObject(json);
52-
out.println("<h2>"
53-
+ jo.getJSONObject("value").getString("joke")
54-
+ "</h2>");
55-
out.println("</body></html>");
48+
JSONObject jo = new JSONObject(json.toString());
49+
50+
req.setAttribute("joke", jo.getJSONObject("value").getString("joke"));
51+
req.getRequestDispatcher("/main.jsp").forward(req, resp);
5652
}
53+
54+
@Override
55+
public void doPost(HttpServletRequest req, HttpServletResponse resp)
56+
throws IOException, ServletException {
57+
58+
String id = req.getParameter("id");
59+
String text = req.getParameter("text");
60+
61+
if (id == null || text == null || id == "" || text == "") {
62+
req.setAttribute("error", "invalid input");
63+
req.getRequestDispatcher("/main.jsp").forward(req,resp);
64+
return;
65+
}
66+
67+
JSONObject jsonObj = new JSONObject()
68+
.put("userId", 33)
69+
.put("id", id)
70+
.put("title", text)
71+
.put("body", text);
72+
73+
// [START complex]
74+
URL url = new URL("http://jsonplaceholder.typicode.com/posts/"+id);
75+
HttpURLConnection conn = (HttpURLConnection) url.openConnection();
76+
conn.setDoOutput(true);
77+
conn.setRequestMethod("PUT");
78+
79+
OutputStreamWriter writer = new OutputStreamWriter(conn.getOutputStream());
80+
writer.write(URLEncoder.encode(jsonObj.toString(), "UTF-8"));
81+
writer.close();
82+
83+
int respCode = conn.getResponseCode(); // New items get NOT_FOUND on PUT
84+
if (respCode == HttpURLConnection.HTTP_OK || respCode == HttpURLConnection.HTTP_NOT_FOUND) {
85+
req.setAttribute("error", "" );
86+
StringBuffer response = new StringBuffer();
87+
String line;
88+
89+
BufferedReader reader = new BufferedReader(new InputStreamReader(conn.getInputStream()));
90+
while ((line = reader.readLine()) != null) {
91+
response.append(line);
92+
}
93+
reader.close();
94+
req.setAttribute("response", response.toString());
95+
} else {
96+
req.setAttribute("error", conn.getResponseCode()+" "+conn.getResponseMessage());
97+
}
98+
// [END complex]
99+
req.getRequestDispatcher("/main.jsp").forward(req, resp);
100+
}
101+
57102
}
Lines changed: 48 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,48 @@
1+
<%--
2+
Copyright 2016 Google Inc. All Rights Reserved.
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 http://www.apache.org/licenses/LICENSE-2.0
7+
Unless required by applicable law or agreed to in writing, software
8+
distributed under the License is distributed on an "AS IS" BASIS,
9+
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
10+
See the License for the specific language governing permissions and
11+
limitations under the License.
12+
--%>
13+
<%@ page contentType="text/html;charset=UTF-8" language="java" %>
14+
<!DOCTYPE html>
15+
<!-- [START base] -->
16+
<%@ taglib uri="http://java.sun.com/jsp/jstl/core" prefix="c" %>
17+
<%@ taglib uri="http://java.sun.com/jsp/jstl/functions" prefix="fn" %>
18+
<html lang="en">
19+
<head>
20+
<title>URL Fetch sample</title>
21+
<meta charset="utf-8">
22+
<meta name="viewport" content="width=device-width, initial-scale=1">
23+
</head>
24+
<body>
25+
<h1 align="center">URL Fetch Sample</h1>
26+
<c:if test="${not empty joke}">
27+
<h2>Joke: ${joke}</h2>
28+
</c:if>
29+
<p /><p />
30+
<c:if test="${not empty error}">
31+
<h2>${error}</h2>
32+
</c:if>
33+
<p />
34+
<c:if test="${not empty response}">${response}</c:if>
35+
<p />
36+
<p>
37+
<form method="post">
38+
<label for="id">&nbsp;&nbsp;ID:</label><input type="text" name="id" value="777"/><br />
39+
<label for="text">Text:</label><input type="text" name="text" value="Lorem ipsum dolor sit amet, consectetur adipiscing elit."/><br />
40+
<input type="submit" value="Send"/>
41+
</form>
42+
</p>
43+
<c:if test="">
44+
45+
</c:if>
46+
</body>
47+
</html>
48+
<!-- [END base]-->

0 commit comments

Comments
 (0)