Android App连接到JSP页面

时间:2015-05-30 14:16:11

标签: java android mysql jsp

我正在尝试将我的Android应用程序连接到JSP页面,以便从同一服务器上的数据库中获取数据。我的网页运行正常,在这里你可以看到代码:

associazioni.jsp

    <%@ page language="java" contentType="text/html; charset=ISO-8859-1" pageEncoding="ISO-8859-1"%>
    <%@ page import="java.sql.Connection" %>
    <%@ page import="java.sql.DriverManager" %>
    <%@ page import="java.sql.ResultSet" %>
    <%@ page import="java.sql.ResultSetMetaData" %>
    <%@ page import="java.sql.SQLException" %>
    <%@ page import="java.sql.Statement" %>
<%
try {

    Class.forName("com.mysql.jdbc.Driver").newInstance();
    // crea un collegamento con il database "csv"
    Connection conn = DriverManager.getConnection("jdbc:mysql://localhost/csv", "username", "password");
    Statement stat = conn.createStatement();
    // esegue la query di selezione
    ResultSet rs = stat.executeQuery("SELECT * FROM associazioni");

    // scrive che tutto è andato a buon fine
    out.println("OK");

    // scrive i dati
    while (rs.next()) {
        // id_associazione
        out.println(rs.getString(1));
        // nome
        out.println(rs.getString(2));
        // indirizzo
        out.println(rs.getString(3));
        // telefono
        out.println(rs.getString(4));
        // contatti
        out.println(rs.getString(5));
        // descrizione
        out.println(rs.getString(6));
    }

    // scrive che il processo è concluso
    out.println("END");

    // chiude la connessione
    stat.close();
    conn.close();

// cattura le eccezioni
} catch (Exception e) {
    // scrive il tipo di eccezione
    out.println(e.toString());
}
%>

你可以证明自己,如果你去: http://liceocuneoweb2.linuxd.org:8080/CSV/associazioni.jsp 网页正在工作,写作&#34; OK&#34;在开始和&#34;结束&#34;在文件的末尾。 当我尝试从应用程序访问它时出现问题,我写下你的代码,如果你可以建议我更好的方法来编写它,或者只是解决问题,我将非常感激!

MainActivity.java

public class MainActivity extends Activity {

    private TextView resultsTV;
    private BufferedReader reader;
    private String result;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        resultsTV = (TextView) findViewById(R.id.results);
        new RetrieveResults().execute();
    }

    @Override
    public boolean onCreateOptionsMenu(Menu menu) {
        // Inflate the menu; this adds items to the action bar if it is present.
        getMenuInflater().inflate(R.menu.menu_main, menu);
        return true;
    }

    @Override
    public boolean onOptionsItemSelected(MenuItem item) {
        // Handle action bar item clicks here. The action bar will
        // automatically handle clicks on the Home/Up button, so long
        // as you specify a parent activity in AndroidManifest.xml.
        int id = item.getItemId();

        //noinspection SimplifiableIfStatement
        if (id == R.id.action_settings) {
            return true;
        }

        return super.onOptionsItemSelected(item);
    }

    private void leggi() {
        try {
            ArrayList<String> pagina = new ArrayList<String>();
            while (true) {
                String r = this.reader.readLine();
                if (r.equals("END")) {
                    break;
                } else {
                    pagina.add(r);
                }
            }
            scriviResults(pagina);
        } catch (Exception e) {
            resultsTV.setText(e.toString());
        }
    }

    private void scriviResults(ArrayList<String> pagina) {
        for (int i=0; i<pagina.size(); i++) {
            resultsTV.append(pagina.get(i) + "\n");
        }
    }

    private class RetrieveResults extends AsyncTask {
        @Override
        protected Object doInBackground(Object[] params) {
            collegati();
            return null;
        }

        @Override
        protected void onPostExecute(Object o) {
            if (result.equals("OK")) {
                leggi();
            } else {
                resultsTV.setText("Errore");
            }
        }
    }

    private void collegati() {
        try {
            String link = "http://liceocuneoweb2.linuxd.org:8080/CSV/associazioni.jsp";
            URL url = new URL(link);
            URLConnection conn = url.openConnection();
            reader = new BufferedReader(new InputStreamReader(conn.getInputStream()));
            result = reader.readLine();
        } catch (Exception e) {
            resultsTV.setText(e.toString());
        }
    }
}

这个程序没有按照我的意愿工作,它应该连接到服务器并开始读取行,如果第一个字符串是&#34; OK&#34;然后它读取另一个直到&#34;结束&#34;并将数据放在ArrayList中。在程序结束时,它通过TextView输出Array。 有时它会给我&#34; Errore&#34;,有时它无法连接到服务器,它永远不会回馈整个数据库表。我不知道该尝试什么,代码似乎对我来说是正确的。 谢谢你的时间,抱歉我的英语不好!

1 个答案:

答案 0 :(得分:0)

使用Servlet而不是Servlet Page来生成响应。

此外,不是使用行分隔响应,而是使用JSON api创建JSON对象或数组,并将信息映射到该对象或数组。使用write方法将JSONObject写入您的响应。 JSONObject Javadoc

在MainActivity.java中,要检索您的信息,请使用Java HttpURLConnection创建HTTP GET请求。一旦您将响应字符串解析为JSONObject并访问该信息以进行进一步处理。 The example in this link explains how to create a HTTP Connection and send a GET request

编辑: 由于我没有结果集,因此我简化了servlet的解决方案。

import java.io.IOException;
import java.io.PrintWriter;
import java.io.Writer;
import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import org.json.JSONArray;
import org.json.JSONObject;

@WebServlet(name = "JSONResponseExample", urlPatterns = {"/JSONResponseExample"})
public class JSONResponseExample extends HttpServlet {

    @Override
    protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        final PrintWriter writer = response.getWriter();
        final JSONArray jsonArray = new JSONArray();

        response.setContentType("application/json");
        response.setCharacterEncoding("UTF-8");        

        JSONObject item1 = new JSONObject();
        item1.put("id", "1");
        item1.put("name", "name 1");
        item1.put("email", "Email Adderess 1");
        jsonArray.put(item1);

        JSONObject item2 = new JSONObject();
        item2.put("id", "2");
        item2.put("name", "name 2");
        item2.put("email", "Email Adderess 2");
        jsonArray.put(item2);

        Writer jsonWriter = jsonArray.write(writer);
        jsonWriter.close();
    }
}

对发送到此servlet的任何GET请求的响应将是:

[
   {
       "id": "1",
       "name": "name 1",
       "email": "Email Address 1"
   },
   {
       "id": "2",
       "name": "name 2",
       "email": "Email Address 2"
   }
]

从HTTPRequest获得String响应后,您可以通过以下方式解析它:

JSONArray array = new JSONArray(responseString);

for(int i = 0; i < array.length(); i++){
  JSONObject item = array.get(i);
  String name = item.get("name");
  String email = item.get("email");
  // ... You get the Idea.
}

您可以从任何maven存储库下载JSON jar文件。 central.maven.org/maven2/org/json/json/20141113/json-20141113.jar