如何从android发送数据到服务器

时间:2010-07-01 10:35:11

标签: android http httpclient http-post

我正在探索从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 个答案:

答案 0 :(得分: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;
}

你可以检查一下here关于解析android中json的类似问题的示例代码。

This也可能有用。