How do i Send POST method with the JSON data (java)?

我怕爱的太早我们不能终老 提交于 2019-12-08 08:36:59

问题


i need toSend POST method with the JSON data ,Make sure i need to send JSON Object serialized into string. Not the JSON string itself.so how can i implement this using JAVA


回答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;
}

For more you can see this example.




回答2:


I would recommend using Jersey REST framework which works great with GAE. Here is a demo.




回答3:


Using gson, you can POST JSON data to a web-service very easily.

For example:

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

Now send the POJO to a real web-service:

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
    }
}

Replies with:

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

(Note, the equivalent cURL command at time of writing was) ->

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


来源:https://stackoverflow.com/questions/10071009/how-do-i-send-post-method-with-the-json-data-java

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!