简体   繁体   English

如何使用doGet方法捕获从android应用发送到servlet的JSON对象?

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

I want to take username, password & email-id from user, construct a JSON object and send it to a java servlet, which then reads it and insert it into MySql object. 我想从用户那里获取用户名,密码和电子邮件ID,构造一个JSON对象并将其发送到Java Servlet,然后将其读取并将其插入MySql对象。 I have done using this a php server (source: http://www.androidhive.info/2011/10/android-login-and-registration-screen-design/ ) but I need to do this with the help of java servlet. 我已经使用了这个php服务器(来源: http : //www.androidhive.info/2011/10/android-login-and-registration-screen-design/ ),但是我需要在Java Servlet的帮助下完成此操作。 Earlier I was doing this by passing url parameters as follows and it is working properly, but now I want to use the information as JSON parameter: 早些时候,我通过如下传递url参数来做到这一点,并且它可以正常工作,但是现在我想将该信息用作JSON参数:

Android Code: 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 Code: 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");

I had a look at this (http://stackoverflow.com/questions/11074934/the-json-object-sent-from-android-application-is-null-when-i-want-to-access-him) but couldn't understand. 我看了一下(http://stackoverflow.com/questions/11074934/the-json-object-sent-from-android-application-is-null-when-i-want-to-access-him),但是听不懂

JSON code is as follows (source: http://www.androidhive.info/2011/10/android-login-and-registration-screen-design/ ): 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;
    }

First you are creating a Post request. 首先,您要创建一个发布请求。 it is generally recommended to call the post from get. 通常建议从get致电该职位。

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

This is what I do to build a JSON object frot he request 这就是我要构建他请求的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);
}

You can use simple serialization instead by writing prepared JSONObject object and serializing it to the servlet. 您可以通过编写准备好的JSONObject对象并将其序列化到servlet来使用简单的序列化。 Serialization is really handy if you are communicating from java to java. 如果您正在从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);

And from the servlet 并从servlet

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

You can pass even complex serializable objects through this method. 您甚至可以通过此方法传递复杂的可序列化对象。 You can write objects from service and read at client as well. 您可以从服务写入对象,也可以在客户端读取。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM