使用NameValuePair将整数发送到HTTP服务器

5

我希望用NameValuePair方法从Android客户端向Web服务器发送一些值:

public void postData() {
        // Create a new HttpClient and Post Header
        HttpClient httpclient = new DefaultHttpClient();
        HttpPost httppost = new HttpPost("http:/xxxxxxx");

        try {
            // Add your data
            List<NameValuePair> nameValuePairs = new ArrayList<NameValuePair>(1);
            String amount = paymentAmount.getText().toString();
            String email = inputEmail.getText().toString();
            nameValuePairs.add(new BasicNameValuePair("donationAmount", amount));
            nameValuePairs.add(new BasicNameValuePair("email", email));
            nameValuePairs.add(new BasicNameValuePair("paymentMethod", "5"));
            httppost.setEntity(new UrlEncodedFormEntity(nameValuePairs));

            // Execute HTTP Post Request
            HttpResponse response = httpclient.execute(httppost);

        } catch (ClientProtocolException e) {
            // TODO Auto-generated catch block
        } catch (IOException e) {
            // TODO Auto-generated catch block
        }
    } 

很不幸,NameValuePair 只能发送字符串,我需要发送整数值。

3个回答

13

嗨,hectichavana。如果你想使用名称值对发送整数值,你可以尝试像这样做:

nameValuePairs.add(new BasicNameValuePair("gender",Integer.toString(1)));

gender代表键,1将成为该键的值。希望这可以帮到你。


我在Spinner中有五个不同名称的值,如a、b、c、d、e、f。我想传递这些字符串值的整数值...怎么做?<string-array name="planets_array"> <item value="1">a</item> <item value="2">b</item> <item value="3">c</item> <item value="4">d</item> <item value="5">e</item> <item value="6">f</item> </string-array> - user4050065
@AdityaVyas,请在新帖中提出新问题。 - Daryl Bennett
只需要从下拉菜单中获取所选值,即可使用 Integer.toString() 方法将整数转换为字符串。@DarylBennett 是正确的,你的问题与本主题无关。 - Roshan Jha

2

我认为你发出的post请求的另一端不会关心客户端使用的值格式,而是将其全部视为字符串。因此,在我看来,这就是NameValuePair只接受String的原因。
如果您的数据是以数字格式存在的,您可以随时将其转换回String,并使用NameValuePair进行配对。

new BasicNameValuePair("integer", new Integer().toString(value));

这是我经常使用的一个例子。


1

如果我说的显而易见或者错过了重点,那么请原谅。自然的解决方案似乎是将整数转换为字符串,然后在服务器端进行转换。更完整的解决方案是使用不同的表示形式(例如XML)来编码数据。


网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接