簡體   English   中英

如何使用doGet方法捕獲從android應用發送到servlet的JSON對象?

[英]How can I catch a JSON object sent from an android app to a servlet with doGet method?

我想從用戶那里獲取用戶名,密碼和電子郵件ID,構造一個JSON對象並將其發送到Java Servlet,然后將其讀取並將其插入MySql對象。 我已經使用了這個php服務器(來源: http : //www.androidhive.info/2011/10/android-login-and-registration-screen-design/ ),但是我需要在Java Servlet的幫助下完成此操作。 早些時候,我通過如下傳遞url參數來做到這一點,並且它可以正常工作,但是現在我想將該信息用作JSON參數:

Android代碼:

try {
                url = new URL("http://10.0.2.2:8080/Servlet/Servlet?param1="
                        + uname + "&param2=" + pwd + "&param3=" + eid);
                // url = new URL("http://10.0.2.2:8080/Servlet/Servlet");
                HttpURLConnection urlConnection = (HttpURLConnection) url
                        .openConnection();
                InputStream in = new BufferedInputStream(
                        urlConnection.getInputStream());

                urlConnection.disconnect();

            } catch (Exception e) {
                e.printStackTrace();
            }

Servlet代碼:

protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException
    {

        req.setCharacterEncoding("UTF-8");
        resp.setCharacterEncoding("UTF-8");
        final String uname = req.getParameter("param1");
        final String pwd = req.getParameter("param2");
        final String eid = req.getParameter("param3");

我看了一下(http://stackoverflow.com/questions/11074934/the-json-object-sent-from-android-application-is-null-when-i-want-to-access-him),但是聽不懂

JSON代碼如下(來源: http : //www.androidhive.info/2011/10/android-login-and-registration-screen-design/ ):

public class JSONParser {

    static InputStream is = null;
    static JSONObject jObj = null;
    static String json = "";

    // constructor
    public JSONParser() {

    }

    public JSONObject getJSONFromUrl(String url, List<NameValuePair> params) {

        // Making HTTP request
        try {
            // defaultHttpClient
            DefaultHttpClient httpClient = new DefaultHttpClient();
            HttpPost httpPost = new HttpPost(url);
            httpPost.setEntity(new UrlEncodedFormEntity(params));

            HttpResponse httpResponse = httpClient.execute(httpPost);
            HttpEntity httpEntity = httpResponse.getEntity();
            is = httpEntity.getContent();

        } catch (UnsupportedEncodingException e) {
            e.printStackTrace();
        } catch (ClientProtocolException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        }

        try {
            BufferedReader reader = new BufferedReader(new InputStreamReader(
                    is, "iso-8859-1"), 8);
            StringBuilder sb = new StringBuilder();
            String line = null;
            while ((line = reader.readLine()) != null) {
                sb.append(line + "\n");
            }
            is.close();
            json = sb.toString();
            Log.e("JSON", json);
        } catch (Exception e) {
            Log.e("Buffer Error", "Error converting result " + e.toString());
        }

        // try parse the string to a JSON object
        try {
            jObj = new JSONObject(json);            
        } catch (JSONException e) {
            Log.e("JSON Parser", "Error parsing data " + e.toString());
        }

        // return JSON String
        return jObj;

    }
}



public JSONObject loginUser(String email, String password){
        // Building Parameters
        List<NameValuePair> params = new ArrayList<NameValuePair>();
        params.add(new BasicNameValuePair("tag", login_tag));
        params.add(new BasicNameValuePair("email", email));
        params.add(new BasicNameValuePair("password", password));
        JSONObject json = jsonParser.getJSONFromUrl(loginURL, params);
        // return json
        // Log.e("JSON", json.toString());
        return json;
    }

首先,您要創建一個發布請求。 通常建議從get致電該職位。

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

這就是我要構建他請求的JSON對象的方法

 */
protected void doPost(HttpServletRequest request, HttpServletResponse response)
        throws ServletException, IOException
{

    HttpSession httpSession = request.getSession(false);
    JSONObject jJobObject = JSONObject.fromObject(request.getParameter("data"));
    JJob jJob = (JJob) JSONObject.toBean(jJobObject, JJob.class);
    String strTerm = (String) httpSession.getAttribute("terminal");
    Integer term = null;
    try {
        term = Integer.parseInt(strTerm);
    }
    catch(Exception e) {
        //
    }
    jJob = PersoJobService.createJob(jJob, (Integer) httpSession.getAttribute("userId"), term );
    writeResponse(JSONObject.fromObject(jJob), request, response);
}

您可以通過編寫准備好的JSONObject對象並將其序列化到servlet來使用簡單的序列化。 如果您正在從Java到Java進行通信,則序列化確實非常方便。

Map<Object, Object> data = new Hashtable<Object, Object>(0);
data.put("etc", "etc");
...

URLConnection con = url.openConnection();
con.setDoInput(true);
con.setDoOutput(true);
new ObjectOutputStream(con.getOutputStream()).writeObject(data);

並從servlet

Map<Object, Object> data = (Map<Object, Object>) new ObjectInputStream(request.getInputStream()).readObject();

您甚至可以通過此方法傳遞復雜的可序列化對象。 您可以從服務寫入對象,也可以在客戶端讀取。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM