I am struggling to make an HTTP POST request with JSON object as data.
As you can see below, first I created an HTTP Post request. Then I commented out part of it and attempted to modify it in order to add JSON related code. One of the things that confused me was that despite seeing a number of tutorials using the import "org.json.simple.JSONObject" my IDE reads an error message and states "the import org.json.simple.JSONObject cannot be resolved".
Any advice about how to make this code work would be much appreciated.
import java.io.*;
import java.net.*;
import org.json.simple.JSONObject;
public class HTTPPostRequestWithSocket {
public void sendRequest(){
try {
JSONObject obj = new JSONObject();
obj.put("instructorName", "Smith");
obj.put("courseName", "Biology 101");
obj.put("studentName1", "John Doe");
obj.put("studentNumber", new Integer(100));
obj.put("assignment1", "Test 1");
obj.put("gradeAssignment1", new Double("95.3"));
/*
//Note that this code was taken out in order to attempt to send
//the information in the form of JSON.
String params = URLEncoder.encode("param1", "UTF-8")
+ "=" + URLEncoder.encode("value1", "UTF-8");
params += "&" + URLEncoder.encode("param2", "UTF-8")
+ "=" + URLEncoder.encode("value2", "UTF-8");
*/
String hostname = "nameofthewebsite.com";
int port = 80;
InetAddress addr = InetAddress.getByName(hostname);
Socket socket = new Socket(addr, port);
String path = "/nameofapp";
// Send headers
BufferedWriter wr = new BufferedWriter(new
OutputStreamWriter(socket.getOutputStream(), "UTF8"));
wr.write("POST "+path+" HTTP/1.0rn");
wr.write("Content-Length: "+obj.length()+"rn");
wr.write("Content-Type: application/x-www-form-urlencodedrn");
wr.write("rn");
// Send parameters
wr.write(obj);
wr.flush();
// Get response
BufferedReader rd = new BufferedReader(new InputStreamReader(socket.getInputStream()));
String line;
while ((line = rd.readLine()) != null) {
System.out.println(line);
}
wr.close();
rd.close();
socket.close();//Should this be closed at this point?
}catch (Exception e) {e.printStackTrace();}
}
}