0

我是 Android 的初学者:我有一个 QueryString ="http://www.google.com/Test/?Param1=ABC&Param2=DEF";

我想将此 QueryString 发送到服务器(发出服务器请求。将变量传递到 asp.net 页面并将参数存储到数据库)。

所以我使用 GET 将它发送到服务器。并在AsyncTask<String, Void, Long>

我在 StackOverflow 上找到了这段代码。(我对这段代码做了一些修改)

protected Long doInBackground(String... params) {
        Long result = null;
        HttpResponse response = null;
        try {        
                HttpClient client = new DefaultHttpClient();
                HttpGet request = new HttpGet();
                request.setURI(new URI(params[0]));
                response = client.execute(request);
                result = 1L;
            } catch (URISyntaxException e) {
                e.printStackTrace();
            } catch (ClientProtocolException e) {
                // TODO Auto-generated catch block
                e.printStackTrace();
            } catch (IOException e) {
                // TODO Auto-generated catch block
                e.printStackTrace();
            }   
            return result;
        }

请解释以下两行代码:

request.setURI(new URI(params[0]));
response = client.execute(request);

params[0] 中有什么值和

response = client.execute(request);变量发送到我的asp.net 页面?

编辑 - 另一个问题 - 如果我向 AsyncTask 发送多个字符串

那么对于每个 HTTP-GET 请求,我可以在循环中增加 'i' 来做到这一点吗?

request.setURI(new URI(params[i]));
4

4 回答 4

1

request.setURI(新的 URI(params[0]));

params 是您获得的数组,其中包含传递给 doInBackGround() 的可变长度参数的所有值。您可以使用与传递参数的顺序相对应的索引来检索所需的参数。

响应 = client.execute(request);

它将执行构造的请求,并与服务器端交互。

于 2013-09-04T16:55:47.837 回答
1

在创建和调用 asynctask 执行的地方,您将参数(QueryString)提供给:

protected Long doInBackground(String... params) {

(String... params) 意味着该函数可以有零个或多个字符串值,因此每当您向 doInBackground 提供一个字符串时,它都会收到一个字符串数组(在本例中为您的 QueryString)。要获取查询字符串,您可以使用params[0]

response = client.execute(request);

这将执行创建的请求并在响应对象中获取响应。

于 2013-09-04T16:58:03.283 回答
1

当 Java 中的最后一个值作为 (String x...) 传递时,它与说 (String[] x) 相同,传入一个数组。

调用过程有点不同,当你调用时,你可以传递一个字符串数组,也可以传递一个字符串列表,这些字符串将被组成一个字符串数组。

例如,您可以像这样调用上面的代码:

doInBackground("a","b","c"),你会得到一个包含 3 个元素的 aray params[]。

您的问题--params[0] 将是“a”

于 2013-09-04T16:55:05.067 回答
0

在使用之前,您应该阅读有关 AsyncTask 的信息:http: //developer.android.com/reference/android/os/AsyncTask.html

 params is an array that you pase to the AsyncTask: 
 doInBackground(String... params)// String... params = String [] params

 response = client.execute(request);// yes it will... This line send your request to your service (php, c#, etc, etc)... and on your service you should handle the params your are passing
于 2013-09-04T16:53:54.620 回答