使用Spring-Android调用RESTFul

时间:2012-10-23 09:01:14

标签: java android spring gson

这是我的Strifified json,

 {
       "Request":{
              "Object1":{
                 "Key1":"Value1"
              },
              "Object2":{
                  "Key2":"Value2"
              }
       },
       "Object3":{
                 "Key3":"Value3"
       }
}

我正在使用Gson形成这个。 String Stringifiedjson = new Gson().toJson(user); 这是我想要实现的目标。

RestTemplate rest = new RestTemplate();
String url = "";
String event = rest.getForObject(url, Stringifiedjson);
  1. 如何发送到我的REST服务并在onEventHandleronErrorHandler中取回我的结果。我基本上来自JavaScript背景。
  2. 为什么方法getForObject不接受String, String为params。
  3. 更新

    AuthenticateUser user = new AuthenticateUser(credential, Header);       
    HttpHeaders requestHeaders = new HttpHeaders();
    requestHeaders.setContentType(new MediaType("application","json"));         
    //HttpEntity<AuthenticateUser> requestEntity = new HttpEntity<AuthenticateUser>(user, requestHeaders);
    
    
    RestTemplate restTemplate = new RestTemplate();
    restTemplate.getMessageConverters().add(new MappingJacksonHttpMessageConverter());
    restTemplate.getMessageConverters().add(new StringHttpMessageConverter());
    String url = "url";             
    String result = restTemplate.postForObject(url, AuthenticateUser.class, String.class);
    

    附件是我得到的例外情况。

    http://pastie.org/private/efyfvvbxyxdsvm3lvv7q

2 个答案:

答案 0 :(得分:0)

关于第二个问题:我刚刚找到了这个例子(你可以看看整个文档;))

2.7.1 Basic Usage Example The following example shows a query to google for the search term "SpringSource".

String url = "https://ajax.googleapis.com/ajax/services/search/web?v=1.0&q={query}";

// Create a new RestTemplate instance
RestTemplate restTemplate = new RestTemplate();

// Add the String message converter
restTemplate.getMessageConverters().add(new StringHttpMessageConverter());

// Make the HTTP GET request, marshaling the response to a String
String result = restTemplate.getForObject(url, String.class, "SpringSource");
getForObject

public <T> T getForObject(URI url,
                    Class<T> responseType)
          throws RestClientException
Description copied from interface: RestOperations
Retrieve a representation by doing a GET on the URL . The response (if any) is converted and returned.
Specified by:
getForObject in interface RestOperations
Parameters:
url - the URL
responseType - the type of the return value
Returns:
the converted object
Throws:
RestClientException

您的堆栈跟踪中的异常可能与此post的相同问题有关。当您的应用尝试在主线程中建立连接时,会出现此问题。

答案 1 :(得分:0)

10-23 15:46:10.106: E/AndroidRuntime(1038): FATAL EXCEPTION: main
10-23 15:46:10.106: E/AndroidRuntime(1038): android.os.NetworkOnMainThreadException

在应用程序主ui线程中执行任何网络操作时抛出NetworkOnMainThreadException(另请参阅Keeping Your App Responsive。这是不允许的。您将不得不使用后台线程进行网络操作,请参阅http://developer.android.com/guide/components/processes-and-threads.html

上的工作线程