【问题标题】:Asynchronous HTTP post with JSON parsing the result with Android 4?带有 JSON 的异步 HTTP 帖子使用 Android 4 解析结果?
【发布时间】:2012-07-11 15:57:12
【问题描述】:

我对 Android 还是很陌生。我一直在寻找一个关于如何通过网络执行 HTTP 发布请求的好例子,但我正在犹豫使用哪个,因为我只为 Android 4 开发。我想要一些异步、快速和简单的东西。非常感谢 JSON 结果解析的示例。有任何想法吗?我应该使用 Apache HTTP 客户端还是 HttpURLConnection?

【问题讨论】:

    标签: android json http http-post


    【解决方案1】:

    对我来说,RestTemplate 是在 Android 上使用 REST 服务的最简单方法之一。

    JSON 示例:

    RestTemplate template = new RestTemplate();
            HttpComponentsClientHttpRequestFactory requestFactory = new HttpComponentsClientHttpRequestFactory();
    
        //setting timeout
        requestFactory.getHttpClient().getParams().setIntParameter(CoreConnectionPNames.CONNECTION_TIMEOUT,
                HTTP_TIMEOUT);
        requestFactory.getHttpClient().getParams().setIntParameter(CoreConnectionPNames.SO_TIMEOUT,
                HTTP_TIMEOUT);
    
        template.setRequestFactory(requestFactory);
    
        //setting converter for JSON
        List<HttpMessageConverter<?>> converters = template.getMessageConverters();
        converters.add(new MappingJacksonHttpMessageConverter());
        template.setMessageConverters(converters);
    
    
        ResponseEntity<ResponseObject> response = template.postForEntity(URL, requestObject, ResponseObject.class);
    
        ResponseObject result = response.getBody();
    

    要使这项工作有效,您的项目中需要 RestTemplate 和 jackson(我认为应该是 jackson-all)jar。您可以在 RestTemplate 文档中找到这些 jar 的链接(上面的链接)。

    要使这个异步使用 Android SDK 中的 AsyncTask。

    【讨论】:

      猜你喜欢
      • 2014-03-23
      • 1970-01-01
      • 1970-01-01
      • 2014-03-07
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多