我正在努力发出一个以 JSON 对象作为数据的 HTTP POST 请求。
正如您在下面看到的,首先我创建了一个 HTTP Post 请求。然后我注释掉它的一部分并尝试修改它以添加 JSON 相关代码。让我感到困惑的一件事是,尽管看到了许多使用导入“org.json.simple.JSONObject”的教程,但我的 IDE 读取了一条错误消息并指出“导入 org.json.simple.JSONObject 无法解析”。
任何有关如何使此代码工作的建议都将不胜感激。
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();}
}
}
最佳答案
您的 IDE 说它无法解析导入 org.json.simple.JSONObject
的原因是因为未包含 org.json.simple.*
包和类在 Java 中,而是属于 JSON Simple library .
关于java - 以 JSON 对象作为数据的 HTTP POST 请求,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/26344943/