Android AsyncTask 与 Spring 网络服务

Android AsyncTask with Spring web-services

我在 android 中遇到 AsyncTask 问题。在 android 编程中,我是初学者,我找不到任何解决方案。

这是我的代码

onCreate 函数

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

    final Button submitButton = (Button) findViewById(R.id.get_ingredient);
    submitButton.setOnClickListener(new View.OnClickListener() {
        public void onClick(View v) {
            new Task().execute();
        }
    });
}

和我的私人任务 class with doInBackground

private class Task extends AsyncTask<Void, Void, Ingredient> {

    @Override
    protected Ingredient doInBackground(Void... params) {
        final String url = getString(R.string.base_uri);

        RestTemplate restTemplate = new RestTemplate();
        Map<String, Integer> param = new HashMap<String, Integer>();
        param.put("id", 1);
        Ingredient ingredient = restTemplate.getForObject(url + "/ingredient/{id}", Ingredient.class, param);

        return ingredient;
    }
}

这是我的错误:

02-03 16:13:47.010    2463-2476/pl.kyniu.app.cookbook E/AndroidRuntime﹕ FATAL EXCEPTION: AsyncTask #1
Process: pl.kyniu.app.cookbook, PID: 2463
java.lang.RuntimeException: An error occured while executing doInBackground()
        at android.os.AsyncTask.done(AsyncTask.java:300)
        at java.util.concurrent.FutureTask.finishCompletion(FutureTask.java:355)
        at java.util.concurrent.FutureTask.setException(FutureTask.java:222)
        at java.util.concurrent.FutureTask.run(FutureTask.java:242)
        at android.os.AsyncTask$SerialExecutor.run(AsyncTask.java:231)
        at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1112)
        at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:587)
        at java.lang.Thread.run(Thread.java:841)
 Caused by: org.springframework.web.client.HttpClientErrorException: 401 Unauthorized
        at org.springframework.web.client.DefaultResponseErrorHandler.handleError(DefaultResponseErrorHandler.java:76)
        at org.springframework.web.client.RestTemplate.handleResponseError(RestTemplate.java:590)
        at org.springframework.web.client.RestTemplate.doExecute(RestTemplate.java:546)
        at org.springframework.web.client.RestTemplate.execute(RestTemplate.java:511)
        at org.springframework.web.client.RestTemplate.getForObject(RestTemplate.java:276)
        at pl.kyniu.app.cookbook.MainActivity$updateTask.doInBackground(MainActivity.java:97)
        at pl.kyniu.app.cookbook.MainActivity$updateTask.doInBackground(MainActivity.java:78)
at android.os.AsyncTask.call(AsyncTask.java:288)
        at java.util.concurrent.FutureTask.run(FutureTask.java:237)
at android.os.AsyncTask$SerialExecutor.run(AsyncTask.java:231)
at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1112)
at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:587)
at java.lang.Thread.run(Thread.java:841)

我做错了什么?

您收到 401 未经授权的 http 响应。在使用其余 api 之前,您必须先处理身份验证。下面是我从 http://docs.spring.io/spring-android/docs/current/reference/html/rest-template.html.

中提取的 http 基本身份验证示例
// Set the username and password for creating a Basic Auth request
HttpAuthentication authHeader = new HttpBasicAuthentication(username, password);
HttpHeaders requestHeaders = new HttpHeaders();
requestHeaders.setAuthorization(authHeader);
HttpEntity<?> requestEntity = new HttpEntity<Object>(requestHeaders);

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

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

try {
    // Make the HTTP GET request to the Basic Auth protected URL
    ResponseEntity<Message> response = restTemplate.exchange(url, HttpMethod.GET, requestEntity, String.class);
    return response.getBody();
} catch (HttpClientErrorException e) {
    Log.e(TAG, e.getLocalizedMessage(), e);
    // Handle 401 Unauthorized response
}