Skip to content

Commit 73f3239

Browse files
committed
Merge pull request #160 from GoogleCloudPlatform/add-post
Add a more complex example as well.
2 parents f78394c + 976ecbe commit 73f3239

File tree

2 files changed

+111
-17
lines changed

2 files changed

+111
-17
lines changed
Lines changed: 63 additions & 17 deletions
Original file line numberDiff line numberDiff line change
@@ -1,11 +1,9 @@
1-
/**
2-
* Copyright 2015 Google Inc. All Rights Reserved.
1+
/*
2+
* Copyright 2016 Google Inc. All Rights Reserved.
33
*
44
* Licensed under the Apache License, Version 2.0 (the "License");
55
* 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
6+
* You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0
97
*
108
* Unless required by applicable law or agreed to in writing, software
119
* distributed under the License is distributed on an "AS IS" BASIS,
@@ -21,9 +19,11 @@
2119
import java.io.BufferedReader;
2220
import java.io.IOException;
2321
import java.io.InputStreamReader;
24-
import java.io.PrintWriter;
22+
import java.io.OutputStreamWriter;
23+
import java.net.HttpURLConnection;
2524
import java.net.URL;
26-
25+
import java.net.URLEncoder;
26+
import javax.servlet.ServletException;
2727
import javax.servlet.http.HttpServlet;
2828
import javax.servlet.http.HttpServletRequest;
2929
import javax.servlet.http.HttpServletResponse;
@@ -33,25 +33,71 @@ public class UrlFetchServlet extends HttpServlet {
3333

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

4038
// [START example]
4139
URL url = new URL("http://api.icndb.com/jokes/random");
4240
BufferedReader reader = new BufferedReader(new InputStreamReader(url.openStream()));
43-
String json = "";
41+
StringBuffer json = new StringBuffer();
4442
String line;
4543

4644
while ((line = reader.readLine()) != null) {
47-
json += line;
45+
json.append(line);
4846
}
4947
reader.close();
5048
// [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>");
49+
JSONObject jo = new JSONObject(json.toString());
50+
51+
req.setAttribute("joke", jo.getJSONObject("value").getString("joke"));
52+
req.getRequestDispatcher("/main.jsp").forward(req, resp);
53+
}
54+
55+
@Override
56+
public void doPost(HttpServletRequest req, HttpServletResponse resp)
57+
throws IOException, ServletException {
58+
59+
String id = req.getParameter("id");
60+
String text = req.getParameter("text");
61+
62+
if (id == null || text == null || id == "" || text == "") {
63+
req.setAttribute("error", "invalid input");
64+
req.getRequestDispatcher("/main.jsp").forward(req, resp);
65+
return;
66+
}
67+
68+
JSONObject jsonObj = new JSONObject()
69+
.put("userId", 33)
70+
.put("id", id)
71+
.put("title", text)
72+
.put("body", text);
73+
74+
// [START complex]
75+
URL url = new URL("http://jsonplaceholder.typicode.com/posts/" + id);
76+
HttpURLConnection conn = (HttpURLConnection) url.openConnection();
77+
conn.setDoOutput(true);
78+
conn.setRequestMethod("PUT");
79+
80+
OutputStreamWriter writer = new OutputStreamWriter(conn.getOutputStream());
81+
writer.write(URLEncoder.encode(jsonObj.toString(), "UTF-8"));
82+
writer.close();
83+
84+
int respCode = conn.getResponseCode(); // New items get NOT_FOUND on PUT
85+
if (respCode == HttpURLConnection.HTTP_OK || respCode == HttpURLConnection.HTTP_NOT_FOUND) {
86+
req.setAttribute("error", "");
87+
StringBuffer response = new StringBuffer();
88+
String line;
89+
90+
BufferedReader reader = new BufferedReader(new InputStreamReader(conn.getInputStream()));
91+
while ((line = reader.readLine()) != null) {
92+
response.append(line);
93+
}
94+
reader.close();
95+
req.setAttribute("response", response.toString());
96+
} else {
97+
req.setAttribute("error", conn.getResponseCode() + " " + conn.getResponseMessage());
98+
}
99+
// [END complex]
100+
req.getRequestDispatcher("/main.jsp").forward(req, resp);
56101
}
102+
57103
}
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)