内容类型为JSON的REST客户端

时间:2015-11-25 13:21:40

标签: json rest

我使用Apache HTTPClient调用带有JSON请求的REST服务,它给出了415不支持的媒体类型错误。

它适用于某些API,但因错误而失败:

DefaultHttpClient httpClient = new DefaultHttpClient();

// Create new getRequest with below mentioned URL
HttpGet getRequest = new HttpGet("example URL");

String encoding = DatatypeConverter.printBase64Binary("usrname:pwd".getBytes("UTF-8"));
getRequest.setHeader("Authorization", "Basic " + encoding);

StringEntity params = new StringEntity("");

params.setContentType("application/json");

// Execute your request and catch response
HttpResponse response = httpClient.execute(getRequest);

// Check for HTTP response code: 200 = success
if (response.getStatusLine().getStatusCode() != 200) {
    throw new RuntimeException("Failed : HTTP error code : " + 
        response.getStatusLine().getStatusCode());
}

// Get-Capture Complete application body response
BufferedReader br = new BufferedReader(new InputStreamReader((
    response.getEntity().getContent())));
String output;
System.out.println("============Output:============");

// Simply iterate through response and show on console.
while ((output = br.readLine()) != null) {
System.out.println(output);

1 个答案:

答案 0 :(得分:0)

我认为您的StringEntity请求中不需要GET。试试以下内容:

getRequest.setHeader(HttpHeaders.CONTENT_TYPE "application/json");