与远程数据库的Android HTTP连接

时间:2011-11-26 06:15:49

标签: android

我有一个Android活动,我想用MYSql数据库连接JSP页面作为中间层来接受来自android的值并在数据库上进行查询。 问题是我无法将参数值从Android Activity发送到JSP页面。应用程序在模拟器启动时崩溃。我已经在清单文件中授予了互联网权限,这可以捕获异常。

public void tryLogin() {
        Log.v(TAG, "Trying to Login");
        EditText etxt_user = (EditText) findViewById(R.id.txt_username);
        EditText etxt_pass = (EditText) findViewById(R.id.txt_password);
        String username = etxt_user.getText().toString();
        String password = etxt_pass.getText().toString(); 
        HttpClient client = new DefaultHttpClient();
        HttpPost httppost = new HttpPost("http://localhost:8084/authen/register.jsp");
        List< BasicNameValuePair > nvps = new ArrayList< BasicNameValuePair >();
        nvps.add(new BasicNameValuePair("username", username));
        nvps.add(new BasicNameValuePair("pass", password));
        try {
              UrlEncodedFormEntity p_entity = new UrlEncodedFormEntity(nvps,"utf-8");

              httppost.setEntity(p_entity);

              HttpResponse response = client.execute(httppost);
              Log.v(TAG, "Sahil Sahil Sahil");

              Log.v(TAG, response.getStatusLine().toString());
              HttpEntity responseEntity = response.getEntity();
              Log.v(TAG, "Set response to responseEntity");

              SAXParserFactory spf = SAXParserFactory.newInstance();
              SAXParser sp = spf.newSAXParser();
              XMLReader xr = sp.getXMLReader();
              LoginHandler myLoginHandler = new LoginHandler();

              xr.setContentHandler(myLoginHandler);
              xr.parse(retrieveInputStream(responseEntity));
              ParsedLoginDataSet parsedLoginDataSet = myLoginHandler.getParsedLoginData(); 
              if (parsedLoginDataSet.getExtractedString().equals("SUCCESS")) {
                    // Store the username and password in SharedPreferences after the successful login
                    SharedPreferences.Editor editor=mPreferences.edit();
                    editor.putString("UserName", username);
                    editor.putString("PassWord", password);
                    editor.commit();
                    Message myMessage=new Message();
                    myMessage.obj="SUCCESS";
                    handler.sendMessage(myMessage); 
              } else if(parsedLoginDataSet.getExtractedString().equals("ERROR")) { 
                    Intent intent = new Intent(getApplicationContext(), LoginError.class);
                    intent.putExtra("LoginMessage", parsedLoginDataSet.getMessage());
                    startActivity(intent); 
                    removeDialog(0);
              } 
        } catch (Exception e) 
        { 
              Intent intent = new Intent(getApplicationContext(), LoginError.class);
              intent.putExtra("LoginMessage", "Unable to login");
              startActivity(intent);
              removeDialog(0);
        }
}

3 个答案:

答案 0 :(得分:0)

这里有一个小例子如何将参数发送到URL ...

import java.net.URL;
import java.net.URLConnection;
import java.net.URLEncoder;
....
        String data = URLEncoder.encode("param1", "UTF-8") + "="
                + URLEncoder.encode(param1, "UTF-8");

        data += "&" + URLEncoder.encode("param2", "UTF-8") + "="
                + URLEncoder.encode(param2, "UTF-8");

        URL url = new URL(http://example.com);
        URLConnection conn = url.openConnection();
        conn.setDoOutput(true);

        OutputStreamWriter wr = new OutputStreamWriter(conn.getOutputStream());
        wr.write(data);
        wr.flush();

答案 1 :(得分:0)

您可以创建一个接受GET格式的XML参数的JSP页面,并对该数据进行操作。

实施例: 您可以创建一个这样的页面,它将接受XML格式的数据:

http://example.com/api/getdb.jsp?data=XML_FORMATED_DATA

假设您有以下XML数据:

   String sXML = "<xml>" +
        "<table>" +
            "<row>" +
                "<name>Alice</name>" +
                "<salary>5000</salary>" +
            "</row>" +
            "<row>" +
                "<name>Bob</name>" +
                "<salary>7000</salary>" +
            "</row>" +
        "</table>" +
    "</xml>" ;

现在您只需在Android代码中执行此操作:

String sUrlEncoded = UrlEncoder.encode(sXML, "utf-8"); // This line encodes XML symbols into URL-friendly characters.

URL url = new URL("http://example.com/api/getdb.jsp?data=" + sUrlEncoded);
URLConnection conn = url.openConnection();

这就是......!

现在,您已使用XML数据作为GET参数调用JSP页面。在JSP中,您需要检索XML数据并解析它,然后执行操作!

就像:(我正在尝试一些JSP!)

String pXML = request.getParameter("data");
// Now parse the content of pXML variable!

提示

为了增加安全性,您可以在网址中包含一个现场生成的会话密钥,如下所示:

http://example.com/api/getdb.jsp?userid=USER_SESSION_KEY&data=XML_FORMATED_DATA

答案 2 :(得分:0)

我的代码中的工作示例......

的Android

HttpPost post = new HttpPost("http://localhost:8080//AddLocation.jsp");
List<NameValuePair> pairs = new ArrayList<NameValuePair>();  
pairs.add(new BasicNameValuePair("id", "007"));  
pairs.add(new BasicNameValuePair("name", "James Bond");  
post.setEntity(new UrlEncodedFormEntity(pairs));
HttpResponse response = client.execute(post);

JSP

request.getParameter("id");
request.getParameter("name");