22
22
import java .io .OutputStreamWriter ;
23
23
import java .net .HttpURLConnection ;
24
24
import java .net .URL ;
25
- import java .net .URLEncoder ;
26
25
import javax .servlet .ServletException ;
27
26
import javax .servlet .annotation .WebServlet ;
28
27
import javax .servlet .http .HttpServlet ;
35
34
@ WebServlet (
36
35
name = "URLFetch" ,
37
36
description = "URLFetch: Write low order IP address to Cloud SQL" ,
38
- urlPatterns = "/urlfetch"
39
- )
37
+ urlPatterns = "/urlfetch" )
40
38
public class UrlFetchServlet extends HttpServlet {
41
39
42
40
@ Override
@@ -67,23 +65,33 @@ public void doPost(HttpServletRequest req, HttpServletResponse resp)
67
65
String id = req .getParameter ("id" );
68
66
String text = req .getParameter ("text" );
69
67
70
- if (id == null || text == null || id == "" || text == "" ) {
68
+ // Validation for id and text inputs.
69
+ if (id == null
70
+ || text == null
71
+ || id .isEmpty ()
72
+ || text .isEmpty ()
73
+ || Integer .parseInt (id ) > 100 ) {
71
74
req .setAttribute ("error" , "invalid input" );
72
75
req .getRequestDispatcher ("/urlfetchresult.jsp" ).forward (req , resp );
73
76
return ;
74
77
}
75
78
76
- JSONObject jsonObj =
77
- new JSONObject ().put ("userId" , 1 ).put ("id" , id ).put ("title" , text ).put ("body" , text );
78
-
79
79
// [START complex]
80
80
URL url = new URL ("http://jsonplaceholder.typicode.com/posts/" + id );
81
81
HttpURLConnection conn = (HttpURLConnection ) url .openConnection ();
82
+ // Enable output for the connection.
82
83
conn .setDoOutput (true );
84
+ conn .setRequestProperty ("Content-Type" , "application/json; charset=UTF-8" );
85
+ conn .setRequestProperty ("Accept" , "application/json" );
86
+ // Set HTTP request method.
83
87
conn .setRequestMethod ("PUT" );
84
88
89
+ // Create JSON request.
90
+ JSONObject jsonObj =
91
+ new JSONObject ().put ("userId" , 1 ).put ("id" , id ).put ("title" , text ).put ("body" , text );
92
+
85
93
OutputStreamWriter writer = new OutputStreamWriter (conn .getOutputStream ());
86
- writer .write (URLEncoder . encode ( jsonObj .toString (), "UTF-8" ));
94
+ writer .write (jsonObj .toString ());
87
95
writer .close ();
88
96
89
97
int respCode = conn .getResponseCode (); // New items get NOT_FOUND on PUT
@@ -92,6 +100,7 @@ public void doPost(HttpServletRequest req, HttpServletResponse resp)
92
100
StringBuffer response = new StringBuffer ();
93
101
String line ;
94
102
103
+ // Read input data stream.
95
104
BufferedReader reader = new BufferedReader (new InputStreamReader (conn .getInputStream ()));
96
105
while ((line = reader .readLine ()) != null ) {
97
106
response .append (line );
0 commit comments