2010-01-08 28 views
2

我想reate POST請求到指定的地址,讓它例如是PostMethod:如何向給定地址發送請求?

http://staging.myproject.com/products.xml?product[title]=TitleTest&product[content]=TestContent&product[price]=12.3&tags=aaa,bbb

POST請求我創建了一個通用的方法:

private String postMethod(String url, HashMap<String, String> headers, String encodedAuthorizationString) throws HttpException, IOException { 
    HttpClient client = new HttpClient(); 
    PostMethod post = new PostMethod(url); 
    post.setRequestHeader("Authorization", encodedAuthorizationString); 
    if(headers != null && !headers.isEmpty()){ 
     for(Entry<String, String> entry : headers.entrySet()){ 
      post.setRequestHeader(new Header(entry.getKey(), entry.getValue())); 
     } 
    } 
    client.executeMethod(post); 
    String responseFromPost = post.getResponseBodyAsString(); 
    post.releaseConnection(); 
    return responseFromPost; 
} 

其中標題代表成對(鍵,值),例如(「product [title]」,「TitleTest」)。我試圖通過調用 postMethod(「http://staging.myproject.com.products.xml」,標題,「xxx」); 其中報頭包括對

( 「產物[標題]」, 「TitleTest」),

( 「產物[內容]」, 「TestContent」),

(產物[價格] , 「12.3」),

( 「標籤」, 「AAA,BBB」)

但服務器返回一個錯誤消息。

有誰知道如何以上述的方法使用它解析地址

http://staging.myproject.com/products.xml?product[title]=TitleTest&product[content]=TestContent&product[price]=12.3&tags=aaa,bbb

?哪部分是網址?參數設置是否正確?

謝謝。

回答

3

我發現了一個問題:

private String postMethod(String url, HashMap<String, String> headers, String encodedAuthorizationString) throws HttpException, IOException { 
    HttpClient client = new HttpClient(); 
    PostMethod post = new PostMethod(url); 
    post.setRequestHeader("Authorization", encodedAuthorizationString); 
    if(headers != null && !headers.isEmpty()){ 
     for(Entry<String, String> entry : headers.entrySet()){ 
      //post.setRequestHeader(new Header(entry.getKey(), entry.getValue())); 
      //in the old code parameters were set as headers (the line above is replaced with the line below) 
      post.addParameter(new Header(entry.getKey(), entry.getValue())); 
     } 
    } 
    client.executeMethod(post); 
    String responseFromPost = post.getResponseBodyAsString(); 
    post.releaseConnection(); 
    return responseFromPost; 
} 

URL = http://staging.myproject.com/products.xml

參數:

( 「產物[標題]」, 「TitleTest」) ,

("product[content]", "TestContent"), 

(product[price], "12.3"), 

("tags", "aaa,bbb") 
1

您似乎混淆了URL查詢參數,例如product [price] = 12.3與HTTP請求標頭。使用setRequestHeader()意味着設置HTTP請求標頭,它是與任何HTTP請求相關聯的元數據。

爲了設置查詢參數,你應該將它們追加到url後面的'?'和UrlEncoded,就像你的示例url。