0

这是我的 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. onEventHandler我将如何发送到我的 REST 服务并在or中取回我的结果onErrorHandler。我基本上来自JavaScript背景。
  2. 为什么 getForObject 方法不接受String, String作为参数。

更新:

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

4

2 回答 2

0

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

2.7.1 基本使用示例 下面的示例显示了对 google 的搜索词“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

您的堆栈跟踪中的异常可能与这篇文章的同一问题有关。当您的应用程序尝试在主线程中建立连接时,就会出现问题。

于 2012-10-23T09:30:52.693 回答
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(另请参阅保持您的应用程序响应。这是不允许的。您必须使用后台线程进行网络操作,请参阅http://上的工作线程developer.android.com/guide/components/processes-and-threads.html

于 2013-08-15T11:50:00.553 回答