RestTemplate相当于cURL PUT

时间:2016-12-18 13:22:53

标签: spring resttemplate

我可以使用该cURL命令访问API:

curl -X PUT -H 'Content-type:application/json' --data-binary '["remaro"]' "http://localhost:4352/mypath"

我想在Spring RestTemplate上完成它。我的数据存储为String。我试过了,但我的服务器返回400错误请求:

HttpHeaders headers = new HttpHeaders(); headers.setContentType(MediaType.APPLICATION_JSON);

HttpEntity<String> entity = new HttpEntity<>("\"" + dataVariable + "\"", headers);
restTemplate.put(http://localhost:4352/mypath, entity);

我还将变量发送为:

String dataVariable = "\"remaro\"";

但没有奏效。我仍然会收到400错误。

2 个答案:

答案 0 :(得分:0)

使用RestTemplate.exchange

查看我的示例并相应更改

String url = BASE_URI + "/update/{clusterId}";

HttpHeaders headers = new HttpHeaders();
headers.setContentType(MediaType.APPLICATION_JSON);


ClusterDTO cluster = new ClusterDTO();
cluster.setClusterId(1L);
cluster.setClusterName("ClusterAV");
..........

HttpEntity<ClusterDTO> entity = new HttpEntity<ClusterDTO>(cluster,headers);
ResponseEntity<ClusterDTO> responseEntity = restTemplate.exchange(url, HttpMethod.PUT, entity, ClusterDTO.class,1L);

答案 1 :(得分:0)

我只是将其发送为:

#include <iostream>

class Boo {
    private:
        int x;
        char y;

    public:
        int getInt() { return x; }
        char getChar() { return y; }
        Boo () { std::cout << "Boo default constructor\n"; }
        Boo ( const Boo& other ) { std::cout << "Boo copy constructor\n"; }
        Boo& operator= ( const Boo& other) { std::cout << "Boo copy assinment\n";
                                            return *this;}

};

class Foo {
    private:
        int x;
        char y;
        static Foo *instance;

    protected:
        Foo() { std::cout << "Foo default constructor\n"; }
        Foo ( const Foo& other ) { std::cout << "Foo copy constructor\n"; }
        Foo& operator=( const Foo& other) { std::cout << "Foo copy assignment\n"; }

    public:
        static Foo & uniqueInst();
        int getInt() { return x; }
        char getChar() { return y; }
};

Foo *Foo::instance = 0;

Foo & Foo::uniqueInst(){
    if(!instance) instance = new Foo();
    return *instance;
};

int main(){
Boo b1; // default constructor
Boo b2; // default constructor
Boo b3 = b1; // copy constructor

b2 = b1;

std::cout << b1.getInt() << std::endl; // Random values since the constructor does nothing
std::cout << b1.getChar() << std::endl;

std::cout << b2.getInt() << std::endl; // Random values since the copy assignment does nothing
std::cout << b2.getChar() << std::endl;

std::cout << b3.getInt() << std::endl; // Random values since the copy constructor does nothing
std::cout << b3.getChar() << std::endl;


Foo *foo;
foo = &Foo::uniqueInst(); // defaulf construtor

std::cout << foo << std::endl;
std::cout << foo->getInt() << std::endl; // Why not random values?
std::cout << foo->getChar() << std::endl;

};

并且工作了。