Android向服务器端发送json数据

时间:2022-12-02 08:45:10

android 向服务器端发送json数据,本文讲解的知识点比较基础,如果你是大神,请直接关闭该网页,免得浪费你宝贵时间。

1.向服务器端发送json数据
  关键代码:

   public void sendJsonToServer() {
HttpClient httpClient = new DefaultHttpClient();
try {

HttpPost httpPost = new HttpPost(constant.url);
HttpParams httpParams = new BasicHttpParams();
List<NameValuePair> nameValuePair = new ArrayList<NameValuePair>();
Gson gson = new Gson();
String str = gson.toJson(initData());
nameValuePair.add(new BasicNameValuePair("jsonString", URLEncoder
.encode(str, "utf-8")));
httpPost.setEntity(new UrlEncodedFormEntity(nameValuePair));
httpPost.setParams(httpParams);
Toast.makeText(Main.this, "发送的数据:\n" + str.toString(),
Toast.LENGTH_SHORT).show();
httpClient.execute(httpPost);
HttpResponse response = httpClient.execute(httpPost);
StatusLine statusLine = response.getStatusLine();
if (statusLine != null && statusLine.getStatusCode() == 200) {
HttpEntity entity = response.getEntity();
if (entity != null) {
Toast.makeText(
Main.this,
"服务器处理返回结果:" + readInputStream(entity.getContent()),
Toast.LENGTH_SHORT).show();
} else {
Toast.makeText(Main.this, "没有返回相关数据", Toast.LENGTH_SHORT)
.show();
}
} else {
Toast.makeText(Main.this, "发送失败,可能服务器忙,请稍后再试",
Toast.LENGTH_SHORT).show();
}
} catch (Exception e) {
throw new RuntimeException(e);
}
}

private static String readInputStream(InputStream is) throws IOException {
if (is == null)
return null;
ByteArrayOutputStream bout = new ByteArrayOutputStream();
int len = 0;
byte[] buf = new byte[1024];
while ((len = is.read(buf)) != -1) {
bout.write(buf, 0, len);
}
is.close();
return URLDecoder.decode(new String(bout.toByteArray()), "utf-8");
}
/*
* 填充数据源
*/
public List<Product> initData() {
List<Product> persons = new ArrayList<Product>();
for (int i = 0; i < 5; i++) {
Product p = new Product();
p.setLocation("所在位置");
p.setName("名称" + i);
persons.add(p);
}
return persons;
}

2.服务器端接收json数据后返回处理结果


3.利用Gson将集合转换成json形式
  如果你还没有听过gson 或是对其不是很熟悉,请先参考 Android解析json数据(Gson),或是百度 谷歌之。  

4.服务器端采用VS建立一个网站,新建一个页面androidtest.aspx
源码:

protected void Page_Load(object sender, EventArgs e)
{
if (Request["jsonString"] != null)
{
string json = Request["jsonString"].ToString().Trim();
json = HttpUtility.UrlDecode(json);
try
{
string str = json.Substring(0, json.Length - 1);//去掉最后一个]
str = str.Substring(1);//去掉第一个[
string[] sArray = Regex.Split(str, "},");
JavaScriptSerializer jss = new JavaScriptSerializer();
for (int i = 0; i < sArray.Length; i++)
{
if (i < sArray.Length - 1)
{
sArray[i] += "}";
}
ProductBillList list = jss.Deserialize<ProductBillList>(sArray[i]);
Response.Write(list.location + list.name + "\n");
}
}
catch
{
Response.Write("出现异常");
}
}
else
{
Response.Write("接收数据失败");
}
}
public class ProductBill
{
public List<ProductBillList> ProductBillLists { get; set; }
}

public class ProductBillList
{
public String name { get; set; }
public String location { get; set; }
}



效果: Android向服务器端发送json数据