如何使用JSON数据(java)发送POST方法?

时间:2012-04-09 08:58:53

标签: java google-app-engine java-ee-6

我需要使用JSON数据发送POST方法,确保我需要将序列化的JSON对象发送到字符串中。不是JSON字符串本身。所以我如何使用JAVA

实现它

3 个答案:

答案 0 :(得分:1)

  public static String sendPostRequest(String postURL) throws Exception{
    String responseStr=null;
    //make POST request
    String jsonContent = "{'name': 'newIndia','columns': [{'name': 'Species','type': 'STRING'}],'description': 'Insect Tracking Information.','isExportable': true}";
    //String data = "{\"document\" : {\"_id\": \"" + id+ "\", \"context\":" + context +"}}";
    URL url = new URL(postURL);
    HttpURLConnection connection = (HttpURLConnection) url.openConnection();

    connection.setDoOutput(true);
    connection.setDoInput(true);
    connection.setInstanceFollowRedirects(false);
    connection.setRequestMethod("POST");
    connection.setRequestProperty("Content-Type", "application/json");
    connection.setRequestProperty("charset", "utf-8");
    connection.setRequestProperty("Content-Length", "" + Integer.toString(jsonContent.getBytes().length));
    connection.setUseCaches(false);

    OutputStreamWriter  writer = new OutputStreamWriter(connection.getOutputStream(), "UTF-8");
    writer.write(jsonContent);       
    writer.close();
    responseStr="Response code: "+connection.getResponseCode()+" and mesg:"+connection.getResponseMessage();

    System.out.println(connection.getResponseMessage());


    InputStream response;                  

    // Check for error , if none store response
    if(connection.getResponseCode() == 200){
        response = connection.getInputStream();
    }else{
        response = connection.getErrorStream();
    }
    InputStreamReader isr = new InputStreamReader(response);
    StringBuilder sb = new StringBuilder();
    BufferedReader br = new BufferedReader(isr);
    String read = br.readLine();
    while(read != null){
        sb.append(read);
        read = br.readLine();
    }  
    // Print the String    
    System.out.println(sb.toString());

    connection.disconnect();
    return responseStr;
}

有关详情,您可以看到此example

答案 1 :(得分:0)

我建议使用适用于GAE的Jersey REST框架。 Here是一个演示。

答案 2 :(得分:0)

使用gson,您可以非常轻松地将JSON数据发布到网络服务。

例如:

public class MyData {                //var myJsonData = {
    private boolean fans = true;     //          fans:true,  
    private boolean funds = true;    //          funds:true
    //private String chart = "day";  //         }
}                                    

现在将POJO发送到真正的网络服务:

public class Main {

    public static void main(String... args) throws Exception {

        URL theUrl = new URL("https://robertsspaceindustries.com/api/stats/getCrowdfundStats");
        Gson gson = new Gson();
        JsonParser jp = new JsonParser();
        MyData thedata = new MyData();

        HttpsURLConnection urlConnection = (HttpsURLConnection) theUrl.openConnection();
        urlConnection.setRequestMethod("POST");
        urlConnection.setDoOutput(true); //allow parameters to be sent/appended 

        DataOutputStream wr = new DataOutputStream(urlConnection.getOutputStream());
        wr.writeBytes(gson.toJson(thedata)); //convert the POJO to JSON, then to binary.
        wr.flush();
        wr.close();

        urlConnection.connect(); //start request transmission

        JsonElement retJson = jp.parse(new InputStreamReader((InputStream) urlConnection.getContent())); //convert the input stream to a json element
        System.out.println(retJson.getAsJsonObject());

        urlConnection.disconnect(); //end request transmission
    }
}

回复:

{"success":1,"{"fans":910125,"funds":8410319141},"code":"OK","msg":"OK"}

(注意,写作时的等效cURL命令是) - >

curl 'https://robertsspaceindustries.com/api/stats/getCrowdfundStats' --data-binary '{"fans":true,"funds":true}'