[http://www.cnblogs.com/xiaoluo501395377/p/3446605.html]

Android客户端解析服务器端的json数据

@WebServlet("/CityServlet")
public class CityServlet extends HttpServlet
{
    private static final long serialVersionUID = 1L;

    public CityServlet()
    {
        super();
    }

    protected void doGet(HttpServletRequest request,
            HttpServletResponse response) throws ServletException, IOException
    {
        this.doPost(request, response);
    }

    protected void doPost(HttpServletRequest request,
            HttpServletResponse response) throws ServletException, IOException
    {
        response.setContentType("text/html;charset=utf-8");
        request.setCharacterEncoding("utf-8");
        response.setCharacterEncoding("utf-8");
        PrintWriter writer = response.getWriter();

        String type = request.getParameter("type");
        if("json".equals(type))
        {
            List<String> cities = new ArrayList<String>();
            cities.add("广州");
            cities.add("上海");
            cities.add("北京");
            cities.add("湖南");
            Map<String, List<String>> map = new HashMap<String, List<String>>();
            map.put("cities", cities);
            String citiesString = JSON.toJSONString(map);
            writer.println(citiesString);
        }

        writer.flush();
        writer.close();
    }

}

如果客户端请求的参数是type=json,则响应给客户端一个json数据格式
接着来看看客户端的代码,首先看看客户端的布局文件,其实就是一个按钮和一个Spinner控件,当点击按钮后,通过http协议请求服务器端的数据,然后在接收到后再更新我们的Spinner控件的数据

<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent" >

    <TextView
        android:id="@+id/textView1"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_alignParentLeft="true"
        android:layout_alignParentTop="true"
        android:layout_marginLeft="64dp"
        android:layout_marginTop="64dp"
        android:textSize="20sp"
        android:text="城市" />

    <Spinner 
        android:id="@+id/spinner"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_alignTop="@id/textView1"
        android:layout_toRightOf="@id/textView1"/>

    <Button
        android:id="@+id/button"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_alignLeft="@+id/textView1"
        android:layout_below="@+id/spinner"
        android:layout_marginLeft="22dp"
        android:layout_marginTop="130dp"
        android:text="加载数据" />

</RelativeLayout>

Android客户端写一个解析json数据格式的类:

public class JsonUtils
{
    /**
     * @param citiesString    从服务器端得到的JSON字符串数据
     * @return    解析JSON字符串数据,放入List当中
     */
    public static List<String> parseCities(String citiesString)
    {
        List<String> cities = new ArrayList<String>();

        try
        {
            JSONObject jsonObject = new JSONObject(citiesString);
            JSONArray jsonArray = jsonObject.getJSONArray("cities");
            for(int i = 0; i < jsonArray.length(); i++)
            {
                cities.add(jsonArray.getString(i));
            }
        }
        catch (Exception e)
        {
            e.printStackTrace();
        }

        return cities;
    }
}

HttpUtils类网络请求类

public class HttpUtils
{
    /**
     * @param path    请求的服务器URL地址
     * @param encode    编码格式
     * @return    将服务器端返回的数据转换成String
     */
    public static String sendPostMessage(String path, String encode)
    {
        String result = "";
        HttpClient httpClient = new DefaultHttpClient();
        try
        {
            HttpPost httpPost = new HttpPost(path);
            HttpResponse httpResponse = httpClient.execute(httpPost);
            if(httpResponse.getStatusLine().getStatusCode() == HttpStatus.SC_OK)
            {
                HttpEntity httpEntity = httpResponse.getEntity();
                if(httpEntity != null)
                {
                    result = EntityUtils.toString(httpEntity, encode);
                }
            }
        }
        catch (Exception e)
        {
            e.printStackTrace();
        }
        finally
        {
            httpClient.getConnectionManager().shutdown();
        }

        return result;
    }
}

MainActivity类:

public class MainActivity extends Activity
{
    private Spinner spinner;
    private Button button;
    private ArrayAdapter<String> adapter;
    private ProgressDialog dialog;
    private final String CITY_PATH_JSON = "http://172.25.152.34:8080/httptest/CityServlet?type=json";
    @Override
    protected void onCreate(Bundle savedInstanceState)
    {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);

        spinner = (Spinner)findViewById(R.id.spinner);
        button = (Button)findViewById(R.id.button);
        dialog = new ProgressDialog(MainActivity.this);
        button.setOnClickListener(new OnClickListener()
        {
            @Override
            public void onClick(View v)
            {
                dialog.setTitle("提示信息");
                dialog.setMessage("loading......");
                dialog.setProgressStyle(ProgressDialog.STYLE_SPINNER);
                dialog.setCancelable(false);

                new MyAsyncTask().execute(CITY_PATH_JSON);
            }
        });
    }

    public class MyAsyncTask extends AsyncTask<String, Void, List<String>>
    {
        @Override
        protected void onPreExecute()
        {
            dialog.show();
        }
        @Override
        protected List<String> doInBackground(String... params)
        {
            List<String> cities = new ArrayList<String>();
            String citiesString = HttpUtils.sendPostMessage(params[0], "utf-8");
            //    解析服务器端的json数据
            cities = JsonUtils.parseCities(citiesString);return cities;
        }
        @Override
        protected void onPostExecute(List<String> result)
        {
            adapter = new ArrayAdapter<String>(MainActivity.this, android.R.layout.simple_spinner_item, result);
            adapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
            spinner.setAdapter(adapter);
            dialog.dismiss();
        }
    }

    @Override
    public boolean onCreateOptionsMenu(Menu menu)
    {
        getMenuInflater().inflate(R.menu.main, menu);
        return true;
    }

}

开启我们的网络授权

Logo

CSDN联合极客时间,共同打造面向开发者的精品内容学习社区,助力成长!

更多推荐