Warning: file_get_contents(/data/phpspider/zhask/data//catemap/4/json/15.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Java 如何将表单数据发布为JSON格式_Java_Json_Rest - Fatal编程技术网

Java 如何将表单数据发布为JSON格式

Java 如何将表单数据发布为JSON格式,java,json,rest,Java,Json,Rest,从我的表单发布参数数据非常有效,但我需要使用JSON发布相同的信息。如何做到这一点。 我的表格是这样的 <form enctype="multipart/form-data" method="post" action="http://myrestfulservice.com/"> <input type="text" name="name"> <input type="text" name="email"> <textarea n

从我的表单发布参数数据非常有效,但我需要使用JSON发布相同的信息。如何做到这一点。 我的表格是这样的

<form enctype="multipart/form-data" method="post" action="http://myrestfulservice.com/">
    <input type="text" name="name">
    <input type="text" name="email">
    <textarea name="about" rows="3"></textarea>
    <input name="file" type="file">
</form>
{
"name":"Josh U",
"email":"xxx@gmail.com",
"about":"Get rich programming or die tryna be something else",
"file":"@/home/josh/image.png"
}
我尝试过使用这个JSON字符串,但得到了以下结果

Exception in thread "main" java.lang.RuntimeException: Failed : HTTP error code : 500
at com.ijoshluisaac.restful.client.RESTFulClientPostUsingJavaHTTPClientLibrary.main(RESTFulClientPostUsingJavaHTTPClientLibrary.java:35)
我的JAVA代码如下所示

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.OutputStream;
import java.net.HttpURLConnection;
import java.net.MalformedURLException;
import java.net.URL;

  public class RESTFulClientPostUsingJavaHTTPClientLibrary {

// JSON content to post
private static final String JSON_OBJECT = "{\"name\":\"Josh U\",\"email\":\"xxx@gmail.com\",\"about\":\"Get rich programming or die tryna be something else\",\"file\":\"/home/josh/image.png\"}";

//Web services URLs
private static final String URL_SR = "http://myrestfulservice.com/";

public static void main(String[] args) {

    try {
        URL url = new URL(URL_SR);
        HttpURLConnection conn = (HttpURLConnection) url.openConnection();
        conn.setDoOutput(true);
        conn.setRequestMethod("POST");
        conn.setRequestProperty("Content-Type", "application/json");


        OutputStream os = conn.getOutputStream();
        os.write(JSON_OBJECT.getBytes());
        os.flush();

        if (conn.getResponseCode() != HttpURLConnection.HTTP_CREATED) {
            throw new RuntimeException("Failed : HTTP error code : "
                    + conn.getResponseCode());
        }

        BufferedReader br = new BufferedReader(new InputStreamReader(
                (conn.getInputStream())));

        String output;
        System.out.println("Successfully Executed RESTFul POST .... \n");
        while ((output = br.readLine()) != null) {
            System.out.println(output);
        }

        conn.disconnect();

    } catch (MalformedURLException e) {

        e.printStackTrace();

    } catch (IOException e) {

        e.printStackTrace();

    }

}
}

使用jquery(因为它提供了许多现成的特性,比如将表单参数序列化为json)并使用下面的代码

var frm = $(document.myform);
var data = JSON.stringify(frm.serializeArray());

 or

var data = $('#yourForm).serializeArray();


我认为您必须执行两个步骤:

  • 首先是将表单内容转换为JS对象(困难的一步)
  • 其次,将JS对象转换为JSON格式(简单步骤)
  • 您只需向添加更多功能即可为我们提供所需的JS对象:

    $.fn.serializeObject = function()
    {
        var o = {};
        var a = this.serializeArray();
        $.each(a, function() {
            if (o[this.name] !== undefined) {
                if (!o[this.name].push) {
                    o[this.name] = [o[this.name]];
                }
                o[this.name].push(this.value || '');
            } else {
                o[this.name] = this.value || '';
            }
        });
        return o;
    };
    

    然后使用
    JSON.stringify
    函数将JS对象转换为JSON格式。您可以找到更多信息

    我认为这将帮助您()为什么在服务器明显需要url编码的表单数据的情况下向服务器发布JSON?jQuery Serialize不生成JSON字符串!
    $.fn.serializeObject = function()
    {
        var o = {};
        var a = this.serializeArray();
        $.each(a, function() {
            if (o[this.name] !== undefined) {
                if (!o[this.name].push) {
                    o[this.name] = [o[this.name]];
                }
                o[this.name].push(this.value || '');
            } else {
                o[this.name] = this.value || '';
            }
        });
        return o;
    };