您的位置:首页 > 移动开发 > Android开发

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

2013-10-07 23:49 861 查看
这个方法,测试成功,详情请见注释package com.android.utils;

import java.io.InputStream;

import java.io.OutputStream;

import java.net.HttpURLConnection;

import java.net.URL;

import org.json.JSONObject;

import android.widget.Toast;

public class Snippet {

    //首先声明一下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: Fiddler

    conn.setRequestProperty("ser-Agent", "Fiddler");

    // 设置contentType

    conn.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 = new JSONObject(json)

    //然后下面这一步是得到{{"username":"zhangsan","age":"12"}

    .getJSONObject("username");

    //下面的Person是一个bean,里面有username,和 age

    Person 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的代码,一个工具类

package com.android.utils;

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 = new ByteArrayOutputStream();

            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));

    }

}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: