0

在android上使用spring restful时出现问题。
我的代码就是这样。
1. 活动

public class TestRestTemplate extends Activity {
    final static String TAG = "TestRestTemplate";

    TextView tvResult;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.test_rest_template);

        tvResult = (TextView) findViewById(R.id.result);
    }

    public void onClick(View view) {
        new MyTask().execute("test");
    }

    private class MyTask extends AsyncTask<String, Void, String> {

        @Override
        protected String doInBackground(String... params) {
            // The URL for making the POST request
            String url = CommonUtilities.SERVER_URL + "/testRestTemplate";

            HttpHeaders requestHeaders = new HttpHeaders();

            // Sending a JSON or XML object i.e. "application/json" or
            // "application/xml"
            requestHeaders.setContentType(MediaType.APPLICATION_JSON);

            // Populate the Message object to serialize and headers in an
            // HttpEntity object to use for the request
            String returnObj = null;
            try {
                HttpEntity<String> requestEntity = new HttpEntity<String>(
                        params[0], requestHeaders);

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

                // Make the network request, posting the message, expecting
                // a String in response from the server
                returnObj = restTemplate.postForObject(url, requestEntity,
                        String.class);
            }catch (NullPointerException e) {
                throw new RuntimeException("resttemplate errors");
            }catch (Exception e) {
                Log.e(TAG + "-Exception", "" + e.getMessage());
            }
            return returnObj;
        }

        @Override
        protected void onPostExecute(String result) {
            tvResult.append("\n" + result);
        }
    }   
}

2. test_rest_template.xml 文件:

<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:orientation="vertical" >

    <Button
        android:id="@+id/button1"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:onClick="onClick"
        android:text="Request Server" />

    <TextView
        android:id="@+id/result"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="Result::" />

</LinearLayout>

3.在服务器端

@Controller
public class HomeController {

    private static final Logger logger = LoggerFactory
            .getLogger(HomeController.class);

    int count = 0;
    @RequestMapping(value = "/testRestTemplate", method=RequestMethod.POST, headers="Accept=application/json")
    public @ResponseBody String getDataFromClient(@RequestBody String clientData) {

        logger.info("request " + (++count) + " times");

        return count + " times request and return client data = " + clientData;
    }
}

问题是,当我第一次单击按钮时,它连接到服务器并成功响应了一个字符串,但之后,如果我等待 21 秒或更长时间,然后单击按钮,我在 logcat 中发生了异常.

12-12 13:56:30.246: W/dalvikvm(1796): threadid=12: thread exiting with uncaught exception (group=0x40a13300)
12-12 13:56:30.266: E/AndroidRuntime(1796): FATAL EXCEPTION: AsyncTask #2
12-12 13:56:30.266: E/AndroidRuntime(1796): java.lang.RuntimeException: An error occured while executing doInBackground()
12-12 13:56:30.266: E/AndroidRuntime(1796):     at android.os.AsyncTask$3.done(AsyncTask.java:299)
12-12 13:56:30.266: E/AndroidRuntime(1796):     at java.util.concurrent.FutureTask$Sync.innerSetException(FutureTask.java:273)
12-12 13:56:30.266: E/AndroidRuntime(1796):     at java.util.concurrent.FutureTask.setException(FutureTask.java:124)
12-12 13:56:30.266: E/AndroidRuntime(1796):     at java.util.concurrent.FutureTask$Sync.innerRun(FutureTask.java:307)
12-12 13:56:30.266: E/AndroidRuntime(1796):     at java.util.concurrent.FutureTask.run(FutureTask.java:137)
12-12 13:56:30.266: E/AndroidRuntime(1796):     at android.os.AsyncTask$SerialExecutor$1.run(AsyncTask.java:230)
12-12 13:56:30.266: E/AndroidRuntime(1796):     at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1076)
12-12 13:56:30.266: E/AndroidRuntime(1796):     at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:569)
12-12 13:56:30.266: E/AndroidRuntime(1796):     at java.lang.Thread.run(Thread.java:856)
12-12 13:56:30.266: E/AndroidRuntime(1796): Caused by: java.lang.RuntimeException: resttemplate errors
12-12 13:56:30.266: E/AndroidRuntime(1796):     at vn.com.bip.personal_schedule.activity.TestRestTemplate$MyTask.doInBackground(TestRestTemplate.java:68)
12-12 13:56:30.266: E/AndroidRuntime(1796):     at vn.com.bip.personal_schedule.activity.TestRestTemplate$MyTask.doInBackground(TestRestTemplate.java:1)
12-12 13:56:30.266: E/AndroidRuntime(1796):     at android.os.AsyncTask$2.call(AsyncTask.java:287)
12-12 13:56:30.266: E/AndroidRuntime(1796):     at java.util.concurrent.FutureTask$Sync.innerRun(FutureTask.java:305)
12-12 13:56:30.266: E/AndroidRuntime(1796):     ... 5 more

我用谷歌搜索这种模式大约 2 天,但没有找到任何有用的建议。你们中的任何人都可以向我解释这个问题。
提前致谢。

4

2 回答 2

0

要调试休息请求,请使用 HttpURLConnection 并将结果记录为字符串。它将允许您跟踪正在发生的事情。您似乎有解析相关的错误。

您是否考虑过使用RoboSpice来执行您的休息请求?它比 AsyncTask 更好。

于 2012-12-12T07:26:17.300 回答
0

它可能不是一个完整的答案,但我找到了解决上述问题的方法。
RestTemplateSimpleClientHttpRequestFactory用于 Android 2.3 (GINGERBREAD) 或更高版本以及HttpComponentsClientHttpRequestFactory低于 2.3 的 Android 版本,因此如果我强制 RestTemplate 必须使用HttpComponentsClientHttpRequestFactory此代码

HttpComponentsClientHttpRequestFactory requestFactory = new HttpComponentsClientHttpRequestFactory();
RestTemplate restTemplate = new RestTemplate(true, requestFactory);

问题已解决。
我没有足够的时间找出问题发生的原因,所以如果你们中的任何专家知道这一点,请
提前为我们分享谢谢。

于 2012-12-13T04:56:18.007 回答