java - 如何将 JSON 对象发布到 URL?

标签 java json httpurlconnection notserializableexception

我正在尝试将 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/

相关文章:

c++ - 在 C++ 中使用 cURL 的 JSON 请求

php - 从 JSON Ajax 返回中提取值

java - 如何使用 HttpURLConnection 获取重定向的 URL 和内容

java - 文件在没有缓冲的情况下流式传输良好,但在缓冲时部分流式传输

java - split() 无法正常工作

java - Google 放置 getPlaceID 返回非空数组但过滤器返回零结果

java - 添加标签的最终 JPanel (java)

c# - 如何将文件路径数组转换为分层 JSON 结构

java - 验证 CXF HttpAsyncClient 对 use.async.http.conduit 上下文属性的使用

java - Java代码无法访问Web Service,但在Chrome中可以正常看到其wsdl