如何将数据从Android发送到服务器

3

我正在探索从Android扫描SSID和RSSI,并且我已经能够做到,但现在我想要将数据发送到服务器,所以我找到了下面的代码。

    HttpClient httpclient = new DefaultHttpClient();
    HttpPost httppost = new HttpPost("http://101.34.45.45/rawData");

    try {
        List<NameValuePair> nameValuePairs = new ArrayList<NameValuePair>(3);
        nameValuePairs.add(new BasicNameValuePair("userId", "00-22-68-E8-EC-F1"));
        nameValuePairs.add(new BasicNameValuePair("timestamp", "2010-07-01 11:11:11"));
        httppost.setEntity(new UrlEncodedFormEntity(nameValuePairs));

        HttpResponse response = httpclient.execute(httppost);
        textView.setText(response.toString());

    } catch (ClientProtocolException e) {
    } catch (IOException e) {
    }

但是现在我添加多个wifi数据时遇到了问题,格式应该如下所示: http://101.34.45.45/rawData?data={"userId":"guest1","timestamp":"2010-07-01 08:58:23","wifi":[{"ssid":"guest","rssi":"40"},{"ssid":"guest1","rssi":"80"}]}
那么如何处理wifi参数呢?有没有人能帮忙一下?我还在尝试几种不同的方法。
谢谢。
1个回答

1
我建议您切换到使用JSON发送数据到服务器。 Google gson 是最容易用来发送和解析JSON的工具。
{"userId":"guest1","timestamp":"2010-07-01 08:58:23","wifi":[{"ssid":"guest","rssi":"40"},{"ssid":"guest1","rssi":"80"}]}

你应该使用一个JSON对象,其中包含一个JSON数组作为其项之一。而JSON数组则包含另一个JSON对象。

如果你正在使用Google GSON,你应该为此构建一个类层次结构。以下是你应该这样做的方法。

Class data{

 String userId;
 String timestamp;
 Wifi wifi;
}

Class Wifi{

 String ssid;
 int rssi;
}

您可以在这里查看有关在Android中解析JSON的类似问题的示例代码。

这个链接也可能很有用。


为什么在Android SDK自带JSON库的情况下,还要引入额外的第三方依赖呢? - Schildmeijer
我发现使用GSON将POJO转换为JSON,以及将JSON转换为POJO比使用内置的JSON库更加容易。 - Primal Pappachan
为什么我们不能使用POST而不是JSON?因为大多数情况下我会发送一张图片到服务器。 - Harsha M V

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