我正在尝试将 JSON 发布到 Web 服务,以便我可以获得 JSON 作为返回响应,我在 Google 中进行了搜索,但我发现的大多数响应是针对 Android 的,而不是针对核心 Java 的,这个问题对于 Swing 应用程序,我将给出我在下面使用的代码。
连接类别
public class Connection extends Thread {
private String url1;
private JSONObject data;
String line;
//Constuctor to initialize the variables.
public Connection(String url1, JSONObject data) {
this.url1 = url1;
this.data = data;
start();
}
public void run() {
ConnectionReaderWriter();
}
//To fetch the data from the input stream
public String getResult() {
return line;
}
public String ConnectionReaderWriter() {
URL url;
HttpURLConnection connection = null;
ObjectOutputStream out;
try {
/*URL url = new URL(Url.server_url + url1); //Creating the URL.
URLConnection conn = url.openConnection(); //Opening the connection.
conn.setDoOutput(true);
OutputStreamWriter wr = new OutputStreamWriter(conn.getOutputStream());
wr.write(data); //Posting the data to the ouput stream.
wr.flush();
BufferedReader rd = new BufferedReader(new InputStreamReader(conn.getInputStream()));
line=rd.readLine(); //Reading the data from the input stream.
wr.close();
rd.close();*/
url = new URL(Url.server_url + url1); //Creating the URL.
connection = (HttpURLConnection) url.openConnection();
connection.setRequestMethod("POST");
connection.setRequestProperty("Content-Type", "application/json");
connection.setRequestProperty("Accept", "application/json");
connection.setRequestProperty("api_key", "123456");
connection.setUseCaches(false);
connection.setDoInput(true);
connection.setDoOutput(true);
//Send request
out = new ObjectOutputStream(connection.getOutputStream());
out.writeObject(data);
out.flush();
out.close();
} catch (MalformedURLException ex) {
Logger.getLogger(Connection.class.getName()).log(Level.SEVERE, null, ex);
String nonet = "No Network Connection";
line = nonet;
} catch (IOException ex) {
Logger.getLogger(Connection.class.getName()).log(Level.SEVERE, null, ex);
String nonet = "No Server Connection";
line = nonet;
}
return line; //Return te stream recived from the input stream.
}
}
注释的代码是我之前在将文本编码传递到 URL 时使用的代码。函数调用如下
JSONObject json = new JSONObject();
json.put("username", username);
json.put("password", passwordenc);
Connection conn = new Connection(Url.login, json);
conn.join();
执行时出现如下异常
Jan 20, 2014 1:18:32 PM SupportingClass.Connection ConnectionReaderWriter
SEVERE: null
java.io.NotSerializableException: org.json.JSONObject
at java.io.ObjectOutputStream.writeObject0(ObjectOutputStream.java:1180)
at java.io.ObjectOutputStream.writeObject(ObjectOutputStream.java:346)
at SupportingClass.Connection.ConnectionReaderWriter(Connection.java:74)
at SupportingClass.Connection.run(Connection.java:40)
请告诉我此代码中的问题或此方法的替代方法。
最佳答案
我来回答:
将 out.writeObject(data);
替换为 out.write(data.toString().getBytes());
您试图编写 JSONObject
对象,而 writeObject()
方法将尝试序列化对象,但由于 JSONObject
类未实现 Serializable,因此会失败。
关于java - 如何将 JSON 对象发布到 URL?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/21228773/