請原諒我的格式是否關閉(新在這裏)。 我有一個像下面REST服務(實現細節省略):如何使用apache commons httpclient和getmethod來讀取modelandview json響應?
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.servlet.ModelAndView;
import org.springframework.web.servlet.view.json.MappingJacksonJsonView;
@Controller
@RequestMapping(value={"/myservice", "/myservice/"}, method=RequestMethod.POST)
public class MyClass{
@RequestMapping(value={"/",""}, method=RequestMethod.GET)
public ModelAndView doSomething(@RequestParam(value="params", required=true) String params){
Map<String,Object> mymap = new HashMap<String,Object>();
mymap.put("myparam",params);
return new ModelAndView(new MappingJacksonJsonView(), mymap);
}
}
我想要做的是寫一個HttpClient的(使用org.apache.commons.httpclient.HttpClient,我知道有另一HttpClient的Apache的在那裏),可以從上述服務獲取「mymap」對象。我知道我必須做類似下面在我的客戶端代碼:
public Map<String,String> getMap(){
HttpClient client = new HttpClient();
HttpMethod method = new GetMethod("myurl");
method.getParams().setParameter(HttpMethodParams.RETRY_HANDLER,
new DefaultHttpMethodRetryHandler(3, false));
NameValuePair [] pair = { new NameValuePair("content","mytestcontentvalue")};
((GetMethod)method).setQueryString(pair);
int code = client.executeMethod(method);
Map<String,String> mymap = ?? /// what do i do here?
return mymap;
}
我一直在尋找一個解決方案,但我不能找到一種方法,在這裏閱讀響應。這是我第一次寫一個客戶端和服務等都可能是我發現了一個解決方案,但永遠無法理解它:( 任何建議,真正幫助!謝謝
感謝您的反饋意見。我相信你可以同時使用getResponseBody和getResponseBodyAsStream()。 – chapstick 2012-02-24 19:13:09