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

标签 java android json servlets

我想从用户那里获取用户名、密码和电子邮件 ID,构造一个 JSON 对象并将其发送到 java servlet,然后 java servlet 读取它并将其插入到 MySql 对象中。我已经使用这个 php 服务器(来源:http://www.androidhive.info/2011/10/android-login-and-registration-screen-design/),但我需要在 java servlet 的帮助下完成此操作。 早些时候我通过如下传递 url 参数来做到这一点并且它工作正常,但现在我想将信息用作 JSON 参数:

安卓代码:

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-他)但听不懂。

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

最佳答案

首先,您要创建一个 Post 请求。一般建议从get调用post。

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

关于java - 如何使用 doGet 方法捕获从 android 应用程序发送到 servlet 的 JSON 对象?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/11242868/

相关文章:

java - 如何在 JavaFX 中创建单例 MainClass?

java - 文件未被写入,已关闭文件

android - 外部数据库和 Android 应用程序

c# - JObject ToObject 不映射

java - 如何使用 Jackson 正确序列化/反序列化 java.time.DayOfWeek?

json - 如何将多个 JSON 文件拉入 Node.js 上的 SWIG 中?

java - 我需要在 WebView 中打开的网页中以编程方式填充文本字段。如何?

java - 使用 Maven 将公共(public)文件夹添加到我的两个模块

java - 从另一个 Activity 中单击按钮时从 Activity 中删除 ListView 项目

android - 如何在选项卡 Activity 的 fragment 中使用 onCreateOptionsMenu? (夏洛克 Action 条)