forked from GoogleCloudPlatform/java-docs-samples
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathUrlFetchServlet.java
More file actions
107 lines (92 loc) · 3.68 KB
/
Copy pathUrlFetchServlet.java
File metadata and controls
107 lines (92 loc) · 3.68 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
/*
* Copyright 2016 Google Inc.
*
* 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.
*/
package com.example.appengine;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.OutputStreamWriter;
import java.net.HttpURLConnection;
import java.net.URL;
import java.net.URLEncoder;
import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import org.json.JSONObject;
@SuppressWarnings("serial")
// With @WebServlet annotation the webapp/WEB-INF/web.xml is no longer required.
@WebServlet(
name = "URLFetch",
description = "URLFetch: Write low order IP address to Cloud SQL",
urlPatterns = "/urlfetch"
)
public class UrlFetchServlet extends HttpServlet {
@Override
public void doGet(HttpServletRequest req, HttpServletResponse resp)
throws IOException, ServletException {
// [START example]
URL url = new URL("http://api.icndb.com/jokes/random");
BufferedReader reader = new BufferedReader(new InputStreamReader(url.openStream()));
StringBuffer json = new StringBuffer();
String line;
while ((line = reader.readLine()) != null) {
json.append(line);
}
reader.close();
// [END example]
JSONObject jo = new JSONObject(json.toString());
req.setAttribute("joke", jo.getJSONObject("value").getString("joke"));
req.getRequestDispatcher("/urlfetchresult.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("/urlfetchresult.jsp").forward(req, resp);
return;
}
JSONObject jsonObj =
new JSONObject().put("userId", 1).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("/urlfetchresult.jsp").forward(req, resp);
}
}