简体   繁体   中英

Unable to get POST data from Spring RestController

I have having trouble with getting Spring to get the POST data. The Controller should be getting the string and then echoing. However, I am getting

response: echo: null

at the main() method

What should I do to fix it?

RestController

@RestController
@RequestMapping("/")
public class HelloWorldController {

    @RequestMapping(method = RequestMethod.GET)
    public String get() {
        return "test get method";
    }

    @RequestMapping(method = RequestMethod.POST)
    public String post(String string) {
        return "echo: " + string;
    }
}

Test POST function

public static void main(String[] args) {
    String urlString = "http://localhost/Test/";
    try{
        Gson gson = new Gson();
        Testz test = new Testz();
        test.setZ("zzzzzzzzzzzzzzzzz");
        test.setCrap("rawrrr!!");
        String urlParameters = gson.toJson(test);
        byte[] postData = urlParameters.getBytes(StandardCharsets.UTF_8);
        URL url = new URL(urlString);
        HttpURLConnection conn = (HttpURLConnection) url.openConnection();
        conn.setDoOutput(true);
        conn.setInstanceFollowRedirects(false);
        conn.setRequestMethod("POST");
        conn.setUseCaches(false);
        try (DataOutputStream wr = new DataOutputStream(conn.getOutputStream())) {
            wr.write(postData);
        } catch (Exception e) {
            e.printStackTrace();
        }

        InputStream inputStream = conn.getInputStream();
        byte[] available = new byte[inputStream.available()];
        inputStream.read(available);

        System.out.println("response: " + new String(available));
    }
    catch(Exception e){
        e.printStackTrace();
    }
}

class Testz {
    private String z = null;
            public void setZ(String z){this.z = z;}
            public String getZ(){return z;}
    private String crap = null;
            public void setCrap(String crap){this.crap = crap;}
            public String getCrap(){return crap;}
}

Try adding the @RequestBody annotation:

public String post(@RequestBody String string) {

It should work like a charm.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM