Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Add a more complex example as well. #160

Merged
merged 4 commits into from
Apr 12, 2016
Merged
Show file tree
Hide file tree
Changes from 3 commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
Original file line number Diff line number Diff line change
@@ -1,12 +1,12 @@
/**
Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

If you use /* (non-Javadoc for license header) you don't need the <p> tags.

* Copyright 2015 Google Inc. All Rights Reserved.
*
* <p>
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* <p>
* http://www.apache.org/licenses/LICENSE-2.0
*
* <p>
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
Expand All @@ -21,9 +21,11 @@
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.PrintWriter;
import java.io.OutputStreamWriter;
import java.net.HttpURLConnection;
import java.net.URL;

import java.net.URLEncoder;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
Expand All @@ -33,25 +35,71 @@ public class UrlFetchServlet extends HttpServlet {

@Override
public void doGet(HttpServletRequest req, HttpServletResponse resp)
throws IOException {
PrintWriter out = resp.getWriter();
out.println("<html><body>");
throws IOException, ServletException {

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

while ((line = reader.readLine()) != null) {
json += line;
json.append(line);
}
reader.close();
// [END example]
JSONObject jo = new JSONObject(json);
out.println("<h2>"
+ jo.getJSONObject("value").getString("joke")
+ "</h2>");
out.println("</body></html>");
JSONObject jo = new JSONObject(json.toString());

req.setAttribute("joke", jo.getJSONObject("value").getString("joke"));
req.getRequestDispatcher("/main.jsp").forward(req, resp);
}

@Override
public void doPost(HttpServletRequest req, HttpServletResponse resp)
throws IOException, ServletException {

String id = req.getParameter("id");
String text = req.getParameter("text");

if (id == null || text == null || id == "" || text == "") {
req.setAttribute("error", "invalid input");
req.getRequestDispatcher("/main.jsp").forward(req, resp);
return;
}

JSONObject jsonObj = new JSONObject()
.put("userId", 33)
.put("id", id)
.put("title", text)
.put("body", text);

// [START complex]
URL url = new URL("http://jsonplaceholder.typicode.com/posts/" + id);
HttpURLConnection conn = (HttpURLConnection) url.openConnection();
conn.setDoOutput(true);
conn.setRequestMethod("PUT");

OutputStreamWriter writer = new OutputStreamWriter(conn.getOutputStream());
writer.write(URLEncoder.encode(jsonObj.toString(), "UTF-8"));
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", "");
StringBuffer response = new StringBuffer();
String line;

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());
}
// [END complex]
req.getRequestDispatcher("/main.jsp").forward(req, resp);
}

}
48 changes: 48 additions & 0 deletions appengine/urlfetch/src/main/webapp/main.jsp
Original file line number Diff line number Diff line change
@@ -0,0 +1,48 @@
<%--
Copyright 2016 Google Inc. All Rights Reserved.

Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
--%>
<%@ page contentType="text/html;charset=UTF-8" language="java" %>
<!DOCTYPE html>
<!-- [START base] -->
<%@ taglib uri="http://java.sun.com/jsp/jstl/core" prefix="c" %>
<%@ taglib uri="http://java.sun.com/jsp/jstl/functions" prefix="fn" %>
<html lang="en">
<head>
<title>URL Fetch sample</title>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1">
</head>
<body>
<h1 align="center">URL Fetch Sample</h1>
<c:if test="${not empty joke}">
<h2>Joke: ${joke}</h2>
</c:if>
<p /><p />
<c:if test="${not empty error}">
<h2>${error}</h2>
</c:if>
<p />
<c:if test="${not empty response}">${response}</c:if>
<p />
<p>
<form method="post">
<label for="id">&nbsp;&nbsp;ID:</label><input type="text" name="id" value="777"/><br />
<label for="text">Text:</label><input type="text" name="text" value="Lorem ipsum dolor sit amet, consectetur adipiscing elit."/><br />
<input type="submit" value="Send"/>
</form>
</p>
<c:if test="">

</c:if>
</body>
</html>
<!-- [END base]-->