从android中的远程服务器获取数据

时间:2012-03-17 17:52:56

标签: android http httprequest httpresponse

我使用oracle db和weblogic作为Web服务器。 从我的Android应用程序,我能够将参数发送到我的远程服务器.. 我的问题是如何从我的服务器到我的Android应用程序获取生成的结果?

如果有人向我提供了一些做这样做的例子,我将非常感激......

String result = "";
//the year data to send
ArrayList<NameValuePair> nameValuePairs = new ArrayList<NameValuePair>();
nameValuePairs.add(new BasicNameValuePair("year","1980"));

//http post
try{
    HttpClient httpclient = new DefaultHttpClient();
    HttpPost httppost = new HttpPost("http://example.com/getAllPeopleBornAfter.php");
    httppost.setEntity(new UrlEncodedFormEntity(nameValuePairs));
    HttpResponse response = httpclient.execute(httppost);
 }

下面给出的代码是我的jsp页面......

<%@ page language="java" contentType="text/html; charset=ISO-8859-1"  
pageEncoding="ISO-8859-1"%> 
<%@page import="java.util.*,java.sql.*"%>

<%!
 Connection con;
 PreparedStatement ps;
 String uname,pass;
 ResultSet rs;
%>

<%
try
{
Class.forName("oracle.jdbc.driver.OracleDriver");
 con=DriverManager.getConnection("jdbc:oracle:thin:@localhost:1521:orcl","pro","pro");

ps=con.prepareStatement("select * from login_stud");

rs=ps.executeQuery();


}
catch(Exception e)
{
e.printStackTrace();
}
%>

我希望我的Android应用程序检索结果集'rs'....并在移动屏幕上显示...如何做到这一点。???如果你想要我的应用程序的详细信息你可以问我@dldnh

2 个答案:

答案 0 :(得分:1)

您可以做的最好的事情是使用RESTFUL Web服务实现JSON。

更多信息:

  1. JSON.ORG

  2. How to create a JSON response

  3. Android包含JSON类,如JSONArray,JSONObject,可用于解释Web Service将返回的响应。点击here了解更多信息。

  4. 你不会出错。 JSON很快,如果您实现RESTFUL身份验证,有很多方法可以保护通信。

    最重要的是,您的Web服务将与iOS应用程序和任何其他支持JSON的平台兼容。

    祝你好运!

答案 1 :(得分:0)

要在android中编写的代码应为:

package com.campuspro.start;

import java.util.ArrayList;
import java.util.List;
import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.NameValuePair;
import org.apache.http.client.HttpClient;
import org.apache.http.client.entity.UrlEncodedFormEntity;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.message.BasicNameValuePair;
import org.apache.http.util.EntityUtils;
import org.json.JSONException;
import org.json.JSONObject;

import android.app.Activity;
import android.app.ProgressDialog;
import android.content.Intent;
import android.os.AsyncTask;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.TextView;


public class Login_Menu extends Activity {

EditText usname;
EditText pass;
TextView tv;
HttpClient client;
HttpPost post;

@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.login_lay);
 tv=(TextView) findViewById(R.id.login_stat_tv);
 usname=(EditText)findViewById(R.id.uname);
 pass=(EditText)findViewById(R.id.pass);
Button login=(Button)findViewById(R.id.login_but);
Button cancel=(Button)findViewById(R.id.cancel_but);

client = new DefaultHttpClient();
String url="http://10.0.2.2:7001/proj/login.jsp";//your url
post = new HttpPost(url);
login.setOnClickListener(new View.OnClickListener() {

    public void onClick(View arg0) {
        new Login().execute("");
    }
});

cancel.setOnClickListener(new View.OnClickListener() {

    public void onClick(View v) {
        usname.getText().clear();
        pass.getText().clear();
    }
});

 }




private class Login extends AsyncTask<String, Void, JSONObject>{
ProgressDialog dialog = ProgressDialog.show(Login_Menu.this, "", "Authenticating, Please wait...");

@Override
protected JSONObject doInBackground(String... params) {
    Log.i("thread", "Doing Something...");
   //authentication operation
try{

    List<NameValuePair> pairs = new ArrayList<NameValuePair>();   
    pairs.add(new BasicNameValuePair("username",usname.getText().toString()));   
    pairs.add(new BasicNameValuePair("password",pass.getText().toString()));   
    post.setEntity(new UrlEncodedFormEntity(pairs));   
    HttpResponse response = client.execute(post);
    int status=response.getStatusLine().getStatusCode();

    if(status == 200)
    {
        HttpEntity e=response.getEntity();
        String data=EntityUtils.toString(e);
        JSONObject last=new JSONObject(data);
        return last;

    }

}

catch(Exception e)
{
    e.printStackTrace();   

}

    return null;
}

protected void onPreExecute(){
    //dialog.dismiss();
    Log.i("thread", "Started...");
    dialog.show();
}
protected void onPostExecute(JSONObject result){
    Log.i("thread", "Done...");
    String status;
    String name;
    try {
        status= result.getString("status");
        name=result.getString("uname");

       if(dialog!=null)
       {
         dialog.dismiss();
       }
       else{}

     if(status.equalsIgnoreCase("yes"))
          {
        tv.setText("Login Successful...");

        Bundle newbundle=new Bundle();
        newbundle.putString("uname",name);

        Intent myIntent=new Intent(Login_Menu.this,Instruction.class);
        myIntent.putExtras(newbundle);

        startActivity(myIntent);

        }
      else{

            tv.setText("No User Found, please try again!");
        }
    } catch (JSONException e) {
        e.printStackTrace();
    }
  }

}

}

服务器端的JSP代码应为:

<%@page contentType="text/html; charset=UTF-8"%>
<%@page import="org.json.simple.JSONObject"%>
<%@page import="java.util.*,java.sql.*"%>

<%!

Connection con;
PreparedStatement ps;
ResultSet rs;
String x,y;

%>

<%
 Class.forName("oracle.jdbc.driver.OracleDriver");

 con=DriverManager.getConnection("jdbc:oracle:thin:@localhost:1521:XE","db_username","db_password");
x=request.getParameter("username");
y=request.getParameter("password");

ps=con.prepareStatement("select * from table_name where suid=? and spwd=?");
ps.setString(1,x);
ps.setString(2,y);
rs=ps.executeQuery();


JSONObject obj=new JSONObject();
if(rs.next())
{
String uname=rs.getString(4);
obj.put("status","yes");
obj.put("uname",uname);
out.print(obj);

}
else
{
obj.put("status","no");
out.print(obj);
}
out.flush();
 %>