0

我正在尝试将我的 android 应用程序连接到服务器上运行的 postgres 数据库,但我遇到了问题。

以下是我的代码,

@TargetApi(Build.VERSION_CODES.GINGERBREAD)
private void download() throws IOException {
    // TODO Auto-generated method stub
    StrictMode.ThreadPolicy policy = new StrictMode.ThreadPolicy.Builder()
            .permitAll().build();
    StrictMode.setThreadPolicy(policy);
    int response = -1;
    InputStream in = null;

    try {
        Class.forName("org.postgresql.Driver");
    } catch (ClassNotFoundException e) {
        e.printStackTrace();
        text.setText((CharSequence) e);}
    try {
    HttpURLConnection conn1;
    String urli = "jdbc:postgresql://"my ip":5432/iwmp_prd?user=postgres";
    conn1 = (HttpURLConnection) DriverManager.getConnection(urli);
URL url = new URL(urli);
        //HttpURLConnection conn1 = url.openConnection();
         conn1.connect();
        if (!(conn1 instanceof HttpURLConnection))
            throw new IOException("Not an HTTP connection");
        //HttpURLConnection httpConn = (HttpURLConnection) conn1;
        //httpConn.setAllowUserInteraction(false);
        //httpConn.setInstanceFollowRedirects(true);
        //httpConn.setRequestMethod("GET");
        //httpConn.connect();

        response = conn1.getResponseCode();
        if (response == HttpURLConnection.HTTP_OK) {
            in = conn1.getInputStream();


            try {
                String nsql = "select user_name from iwmp_user_reg where user_id=?";

                PreparedStatement pstm = ((Connection) conn1).prepareStatement(nsql);
                String user = "DL0000AD";
                pstm.setString(1, user);

                ResultSet rs = pstm.executeQuery();
                while (rs.next()) {
                    String retval = rs.getString(1);
                    text.setText((CharSequence) retval);
                }
                rs.close();
                pstm.close();
                ((Closeable) conn1).close();
            } catch (SQLException e) {
                e.printStackTrace();
                text.setText((CharSequence) e);
            }

        }
    } catch (Exception ex) {
        throw new IOException("Error connecting");
    }

}

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

错误如下,

java.lang.ClassCastException: org.postgresql.jdbc2.Jdbc2Connection cannot be cast to java.net.HttpURLConnection

and it i use HttpURLConnection, then i get an error of 
java.net.MalformedURLException: Unknown protocol: jdbc

我知道我的代码都搞砸了,但我仍在尝试。

4

0 回答 0