2016-05-26 7 views
0

私はRestTemplateでのHttpClientApache Httpclientの代わりにSpring RestTemplateを使用するには?

// build request JSON 
JSONObject json = new JSONObject(); 
json.put("username", username); 
json.put("serial", serial); 
json.put("keyId", keyId); 
json.put("otp", otp); 

String json_req = json.toString();   

// make HTTP request and get response 
HttpPost request = new HttpPost(AuthServer); 
request.setHeader("Content-Type", "application/json"); 
request.setEntity(new StringEntity(json_req)); 

response = client.execute(request); 

でリモートAPI

で作業するための春RestTemplateの代わりにApache HttpClientを使用したい

Map<String, String> paramMap = new HashMap<String,String>(); 
paramMap.put("username", userName); 
paramMap.put("serial", serial); 
paramMap.put("keyId", keyId); 
paramMap.put("otp", otp); 

String mapAsJson = new ObjectMapper().writeValueAsString(paramMap); 

HttpHeaders requestHeaders = new HttpHeaders(); 
requestHeaders.setContentType(MediaType.APPLICATION_JSON); 
HttpEntity<String> request = new HttpEntity<String>(mapAsJson,requestHeaders); 

try { 
    ResponseEntity<String> response = restTemplate.exchange(AuthServer, HttpMethod.POST, request, String.class); 

    return response.getHeaders(); 
} catch (HttpClientErrorException e) { 
    return null; 
} 

}

HttpClient作品でコードが、RestTemplateとしません。 RestTemplateStringEntityの使い方が分かりません。

春バージョンは3.0.0、JVMは1.6です。

答えて

1

RestTemplateは、オブジェクトの操作に適しています。例として:

AuthenticationRequest.java

class AuthenticationRequest { 
    private String username; 
    private String serial; 
    private String key; 
    private String otp; 
} 

AuthenticationResponse.java

class AuthenticationResponse { 
    private boolean success; 
} 

AuthenticationCall.java

class AuthenticationCall { 
    public AuthenticationResponse execute(AuthenticationRequest payload) { 
    HttpEntity<AuthenticationRequest> request = new HttpEntity<AuthenticationRequest>(payload, new HttpHeaders()); 

    return restTemplate.exchange("http://www.domain.com/api/endpoint" 
           , HttpMethod.POST 
           , request 
           , AuthenticationResponse.class).getBody(); 
    } 
} 

次のようにこれらのクラスを使用することができます。

if(new AuthenticationCall().execute(authenticationRequest).isSuccess()) { 
    // Authentication succeeded. 
} 
else { 
    // Authentication failed. 
} 

このすべては、ジャクソンやGSON上などJSONライブラリがあることが必要ですクラスパス

+0

ありがとうございました!私はこれを試してみます。 – yongsup

+0

これは非常に便利な答えですが、私は私の問題を解決することはできません。 私はそのモデルを受け取りますが、webapiはステータス401を返します。 – yongsup

+0

あなたはどんな問題に直面していますか? – manish

関連する問題