android开发案例之使用JSON数据向服务器提交和获取服务器传递的Json数据

来源:互联网 发布:在天猫可以找淘宝店铺 编辑:程序博客网 时间:2024/05/16 03:51
这个方法,测试成功,详情请见注释
//首先声明一下Url
String urlPath = "http://192.168.1.100:8080/test";URL url;try {url = new URL(urlPath);

// 然后我们使用httpPost的方式把lientKey封装成Json数据的形式传递给服务器
// 在这里呢我们要封装的时这样的数据
// {"Person":{"username":"zhangsan","age":"12"}}
//我们首先使用的是JsonObject封装 {"username":"zhangsan","age":"12"}
JSONObject ClientKey = new JSONObject();ClientKey.put("username", "zhangsan");ClientKey.put("age", "12");

//接着我们使用JsonObject封装{"Person":{"username":"zhangsan","age":"12"}}
JSONObject Authorization = new JSONObject();Authorization.put("Person", ClientKey);


//我们把JSON数据转换成String类型使用输出流向服务器写
String content = String.valueOf(Authorization);


// 现在呢我们已经封装好了数据,接着呢我们要把封装好的数据传递过去
HttpURLConnection conn = (HttpURLConnection)url.openConnection();conn.setConnectTimeout(5000);// 设置允许输出conn.setDoOutput(true);conn.setRequestMethod("POST");// 设置User-Agent: Fiddlerconn.setRequestProperty("ser-Agent", "Fiddler");// 设置contentTypeconn.setRequestProperty("Content-Type","application/json");OutputStream os = conn.getOutputStream();os.write(content.getBytes());os.close();


//服务器返回的响应码
int code = conn.getResponseCode();if (code == 200) {

// 等于200了,下面呢我们就可以获取服务器的数据了
Toast.makeText(this, "Post完成", 1).show();
// 在这里我们已经连接上了,也获得了服务器的数据了,
// 那么我们接着就是解析服务器传递过来的数据,
// 现在我们开始解析服务器传递过来的参数,
//假设服务器返回的是{"Person":{"username":"zhangsan","age":"12"}}
InputStream is = conn.getInputStream();//下面的json就已经是{"Person":{"username":"zhangsan","age":"12"}}//这个形式了,只不过是String类型String json = NetUtils.readString(is);//然后我们把json转换成JSONObject类型得到{"Person"://{"username":"zhangsan","age":"12"}}JSONObject jsonObject = newJSONObject(json)//然后下面这一步是得到{{"username":"zhangsan","age":"12"}.getJSONObject("username");//下面的Person是一个bean,里面有username,和 agePerson p= new Person();String username =jsonObject.getString("username");String age = jsonObject.getString("age");//上面已经完整地做出了JSON的传递和解析} else {Toast.makeText(getApplicationContext(), "数据提交失败",1).show();}} catch (Exception e) {e.printStackTrace();}



下面我贴出上面那个netUtils的代码,一个工具类

import java.io.ByteArrayOutputStream;import java.io.InputStream;import java.io.OutputStream;public class NetUtils {public static byte[] readBytes(InputStream is){try {byte[] buffer = new byte[1024];int len = -1 ;ByteArrayOutputStream baos = newByteArrayOutputStream();while((len = is.read(buffer)) != -1){baos.write(buffer, 0, len);}baos.close();return baos.toByteArray();} catch (Exception e) {e.printStackTrace();}return null ;}public static String readString(InputStream is){return new String(readBytes(is));}}


1 1