当前位置: 代码迷 >> JavaScript >> Servlet处置Json请求数据包
  详细解决方案

Servlet处置Json请求数据包

热度:696   发布时间:2012-09-06 10:37:01.0
Servlet处理Json请求数据包
 request.setCharacterEncoding("UTF-8");
		response.setContentType("text/html;charset=UTF-8");
		String acceptjson = "";
		try {
			BufferedReader br = new BufferedReader(new InputStreamReader(
					(ServletInputStream) request.getInputStream(), "utf-8"));
			StringBuffer sb = new StringBuffer("");
			String temp;
			while ((temp = br.readLine()) != null) {
				sb.append(temp);
			}
			br.close();
			acceptjson = sb.toString();
			if (acceptjson != "") {
				JSONObject jo = JSONObject.fromObject(acceptjson);
				JSONArray imgArray = jo.getJSONArray("PartsImages");
				JSONArray infArray = jo.getJSONArray("BasicInfo");
				for (int i = 0; i < imgArray.size(); i++) {
					JSONObject imgObject = JSONObject.fromObject(imgArray
							.get(i));
					System.out.println(imgObject.get("PartsImg"));
				}
				JSONObject infObject = JSONObject.fromObject(infArray.get(0));
				System.out.println(infObject.get("Parts_cate"));
				System.out.println(infObject.get("Company"));
				System.out.println(infObject.get("Parts_name"));
				System.out.println(infObject.get("TEL"));
				System.out.println(infObject.get("Parts_price"));
				System.out.println(infObject.get("Suitable"));
				System.out.println(infObject.get("UsedStyle"));
				System.out.println(infObject.get("Supplement"));
				System.out.println(jo.toString());
			}
			response.getWriter().write(MyReadFile.read("/post/publishsuccess"));
		} catch (Exception e) {
			e.printStackTrace();
			response.getWriter().write(MyReadFile.read("/post/publishfailure"));
		}



import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.util.List;

import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.client.ClientProtocolException;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.entity.StringEntity;
import org.apache.http.impl.client.DefaultHttpClient;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;
import org.json.JSONStringer;

import android.content.Context;
import android.telephony.NeighboringCellInfo;
import android.telephony.TelephonyManager;

public class Location {
    public static String LOCATIONS_URL = "http://www.google.com/loc/json";

    public static String getLocations(Context context) {
        // generate json request
        String jr = generateJsonRequest(context);

        try {
            DefaultHttpClient client = new DefaultHttpClient();

            StringEntity entity = new StringEntity(jr);

            HttpPost httpost = new HttpPost(LOCATIONS_URL);
            httpost.setEntity(entity);

            HttpResponse response = client.execute(httpost);

            String locationsJSONString = getStringFromHttp(response.getEntity());
            
            return extractLocationsFromJsonString(locationsJSONString);
        } catch (ClientProtocolException e) {

            //e.printStackTrace();
        } catch (IOException e) {
            
            //e.printStackTrace();
        } catch (Exception e) {
            //e.printStackTrace();
        }
        return null;

    }

    private static String extractLocationsFromJsonString(String jsonString) {
        String country = "";
        String region = "";
        String city = "";
        String street = "";
        String street_number = "";
        double latitude = 0.0;
        double longitude = 0.0;
        
        //"accuracy":901.0
        double accuracy = 0.0;
        
        try {
            JSONObject jo = new JSONObject(jsonString);
            JSONObject location = (JSONObject) jo.get("location");
            latitude = (Double) location.get("latitude");
            longitude = (Double) location.get("longitude");
            accuracy = (Double) location.get("accuracy");
            JSONObject address = (JSONObject) location.get("address");

            country = (String) address.get("country");
            region = (String) address.get("region");
            city = (String) address.get("city");
            street = (String) address.get("street");
            street_number = (String) address.get("street_number");
        } catch (JSONException e) {

            //e.printStackTrace();
        }

        return "(" + latitude + "," + longitude + ")\t" + country + region + city
                + street + street_number + "\t" + "精确度:" + accuracy;
    }

    // 获取所有的网页信息以String 返回
    private static String getStringFromHttp(HttpEntity entity) {

        StringBuffer buffer = new StringBuffer();

        try {
            // 获取输入流
            BufferedReader reader = new BufferedReader(new InputStreamReader(
                    entity.getContent()));

            // 将返回的数据读到buffer中
            String temp = null;

            while ((temp = reader.readLine()) != null) {
                buffer.append(temp);
            }
        } catch (IllegalStateException e) {
            
            //e.printStackTrace();
        } catch (IOException e) {
            //e.printStackTrace();
        }
        return buffer.toString();
    }

    private static String generateJsonRequest(Context context) {
        TelephonyManager manager = (TelephonyManager) context
                .getSystemService(Context.TELEPHONY_SERVICE);
        List<NeighboringCellInfo> cellList = manager.getNeighboringCellInfo();

        if (cellList.size() == 0)
            return null;

        JSONStringer js = new JSONStringer();
        try {

            js.object();

            js.key("version").value("1.1.0");
            js.key("host").value("maps.google.com");
            js.key("home_mobile_country_code").value(460);
            js.key("home_mobile_network_code").value(0);
            js.key("radio_type").value("gsm");
            js.key("request_address").value(true);
            js.key("address_language").value("zh_CN");

            JSONArray ct = new JSONArray();

            for (NeighboringCellInfo info : cellList) {

                JSONObject c = new JSONObject();
                c.put("cell_id", info.getCid());
                c.put("location_area_code", info.getLac());
                c.put("mobile_country_code", 460);
                c.put("mobile_network_code", 0);
                c.put("signal_strength", info.getRssi()); // 获取邻居小区信号强度

                ct.put(c);
            }
            js.key("cell_towers").value(ct);
            js.endObject();
        } catch (JSONException e) {
            //e.printStackTrace();
            return null;
        }

        return js.toString().replace("true", "True");
    }
}



发送的数据为
{"version":"1.1.0","host":"maps.google.com","home_mobile_country_code":460,"home_mobile_network_code":0,"radio_type":"gsm","request_address":True,"address_language":"zh_CN","cell_towers":[{"mobile_network_code":0,"location_area_code":24803,"cell_id":4364,"signal_strength":24,"mobile_country_code":460},{"mobile_network_code":0,"location_area_code":24803,"cell_id":4361,"signal_strength":27,"mobile_country_code":460},{"mobile_network_code":0,"location_area_code":24611,"cell_id":4381,"signal_strength":28,"mobile_country_code":460},{"mobile_network_code":0,"location_area_code":22831,"cell_id":2702,"signal_strength":29,"mobile_country_code":460},{"mobile_network_code":0,"location_area_code":24802,"cell_id":14962,"signal_strength":99,"mobile_country_code":460},{"mobile_network_code":0,"location_area_code":24802,"cell_id":4703,"signal_strength":22,"mobile_country_code":460}]}

接受到的json数据为

{
"location":
{
"latitude":24.476252,
"longitude":118.16445,
"address":
{
"country":"中国",
"country_code":"CN",
"region":"福建省",
"city":"厦门市",
"street":"前埔西路",
"street_number":"154号"
},
"accuracy":901.0
},
"access_token":"2:NuPu1NEsj5wuRxym:Yvvx7zIaD3oFqYiL"
}

  相关解决方案