2010-01-08 3 views
2

나는 일, 주어진 주소로 POST 요청을 reate 예를 드리고자 나는 보편적 인 방법 만든 POST 요청을PostMethod : 주어진 주소로 요청하는 방법?

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

:

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

을 구문 분석하는 방법을 알고 있나요? 어느 부분이 URL입니까? 매개 변수가 올바르게 설정 되었습니까?

감사합니다.

답변

3

나는 문제를 발견했습니다

("제품 [제목]", "TitleTest") ,

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

(product[price], "12.3"), 

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

HTTP 요청 헤더가있는 product [price] = 12.3과 같이 URL 쿼리 매개 변수가 혼동스러워 보입니다. setRequestHeader()를 사용하면 HTTP 요청 헤더를 설정할 수 있습니다.이 헤더는 모든 HTTP 요청과 연관된 메타 데이터입니다.

검색어 매개 변수를 설정하려면 '?'다음에 URL에 추가해야합니다. 및 URL 예와 같이 UrlEncoded를 사용하십시오.

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

매개 변수 :

관련 문제