2014-11-17 83 views
7

我試圖用放心的方式調用一個休息電話。我的API接受,"application/json"作爲內容類型,我需要在通話中設置。我如下所述設置內容類型。設置內容類型放心

選項1

Response resp1 = given().log().all().header("Content-Type","application/json") 
    .body(inputPayLoad).when().post(addUserUrl); 
System.out.println("Status code - " +resp1.getStatusCode()); 

選項2

Response resp1 = given().log().all().contentType("application/json") 
    .body(inputPayLoad).when().post(addUserUrl); 

我得到的響應是 「415」(表示 「不支持的媒體類型」)。

我試着調用相同的api使用普通的java代碼,它的工作原理。出於某種神祕的原因,我不能通過RA獲得它的工作。

HttpClient client = new DefaultHttpClient(); 
    HttpPost post = new HttpPost(addUserUrl); 
    StringEntity input = new StringEntity(inputPayLoad); 
    input.setContentType("application/json"); 
    post.setEntity(input); 
    HttpResponse response = client.execute(post); 
    System.out.println(response.getEntity().getContent()); 
    /* 
    BufferedReader rd = new BufferedReader(new InputStreamReader(response.getEntity().getContent())); 
    String line = ""; 
    while ((line = rd.readLine()) != null) { 
     System.out.println("Output -- " +line); 
    } 
+0

是否有可能將您的2個第一個示例中的請求標頭與最後一個示例中的標頭進行比較? – spg

+0

選項1: 請求方法:\t POST 請求路徑:\t http://10.75.43。46:7001/supplierapp戰/ PIM/ADDUSER 請求參數:\t 查詢參數:\t 形式PARAMS:\t 路徑參數:\t 頭:\t \t內容類型=應用程序/ JSON 餅乾: \t \t 選項2: 請求方法:\t POST 請求路徑:\t http://10.75.43.46:7001/supplierapp-war/pim/addUser 請求參數:\t個 查詢參數:\t 形式PARAMS:\t 路徑參數:\t 接頭:\t \t內容類型=應用/ JSON 餅乾:\t \t TechRookie

+0

請求由發送的HttpClient: 內容類型:內容 - 類型:application/json 內容長度:203 內容:[email protected] 內容編碼:null 說明: 我使用下面的代碼片段從httpClient獲取標題信息。 System.out.println(「Content Type:」+ input.getContentType()); System.out.println(「Content Length:」+ input.getContentLength()); System.out.println(「Content:」+ input.getContent()); System.out.println(「content Encoding:」+ input.getContentEncoding()); – TechRookie

回答

1

給一個嘗試 給定()​​。contentType中(ContentType.JSON)。體(inputPayLoad.toString)

0

你的第一個選項,您可以請嘗試過加入這個頭和發送請求?

.header("Accept","application/json")

7

我遇到了類似的問題,與其他保證的2.7版本中工作時。我嘗試設置contentType並且接受application/json,但它不起作用。在下面爲我工作的結尾處添加車架提要和換行符。

RestAssured.given().contentType("application/json\r\n") 

的API似乎缺少Content-Type頭後添加新的行字符,由於該服務器不能介質類型和請求內容的其餘部分,並因此引發錯誤415區分 - 「不支持的媒體類型」。

+0

謝謝。這對我們有效。 – Buddha

0

正如在以前的文章中提到有一種方法:

RequestSpecification.contentType(String value)

我並沒有爲我工作了。但是在升級到最新版本(在這個時刻2.9.0)之後,它就可以工作。所以請升級:)

0

這裏是使用CONTENT_TYPE作爲JSON.Hope的完整POST例子,它會幫助你。

RequestSpecification request=new RequestSpecBuilder().build(); 
ResponseSpecification response=new ResponseSpecBuilder().build(); 
@Test 
public void test(){ 
    User user=new User(); 
    given() 
    .spec(request) 
    .contentType(ContentType.JSON) 
    .body(user) 
    .post(API_ENDPOINT) 
    .then() 
    .statusCode(200).log().all(); 
}