您的位置:首页 > 移动开发 > Android开发

android实现从servlet获取数据

2014-12-16 13:10 113 查看

超级心酸,想实现一个简单的android Demo来通过servlet从服务器端来获取数据,查找了好多资料,纠结了将近一天,终于被我实现了,接下来分享一下我的实现过程:

首先来搭建服务器端:

我们先来建一张表:(内容随便添加的,意思意思)

接下来我们来写一下服务端的代码:

工程目录如下:

具体代码:

<span style="font-size:18px;">BookDao.java

package com.lph.dao;

import java.util.List;

import com.lph.entity.Book;

public interface BookDao {
public List<Book> getBooks();

}

Book.java

package com.lph.entity;

public class Book {
private int id;
private String image;
private float price;
private int remark;
private String author;
private String detail;
private String name;

public Book() {
super();
}

public Book(int id, String image, float price, int remark, String author,
String detail, String name) {
super();
this.id = id;
this.image = image;
this.price = price;
this.remark = remark;
this.author = author;
this.detail = detail;
this.name = name;
}

public int getId() {
return id;
}

public void setId(int id) {
this.id = id;
}

public String getName() {
return name;
}

public void setName(String name) {
this.name = name;
}

public int getRemark() {
return remark;
}

public void setRemark(int remark) {
this.remark = remark;
}

public String getAuthor() {
return author;
}

public void setAuthor(String author) {
this.author = author;
}

public String getDetail() {
return detail;
}

public void setDetail(String detail) {
this.detail = detail;
}

public float getPrice() {
return price;
}

public void setPrice(float price) {
this.price = price;
}

public String getImage() {
return image;
}

public void setImage(String image) {
this.image = image;
}

}

BookDaoImpl.java

package com.lph.impl;

import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.ArrayList;
import java.util.List;

import com.lph.dao.BookDao;
import com.lph.entity.Book;
import com.lph.util.DBConn;

public class BookDaoImpl implements BookDao {
private PreparedStatement ps;
private ResultSet rs;
private Connection con;

@Override
public List<Book> getBooks() {

List<Book> books = new ArrayList<Book>();

try {
con = DBConn.getConnection();
String sql = "select * from book";
ps = con.prepareStatement(sql);
rs = ps.executeQuery();
while (rs.next()) {
Book book = new Book(rs.getInt(1), rs.getString(2),
rs.getFloat(3), rs.getInt(4), rs.getString(5),
rs.getString(6), rs.getString(7));
books.add(book);
}
} catch (Exception e) {
System.err.println(e);
} finally {
if (con != null) {
try {
con.close();
} catch (SQLException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
return books;

}

}

WebServletTest.java

package com.lph.servlet;

import java.io.IOException;
import java.io.PrintWriter;
import java.util.List;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import net.sf.json.JSONArray;
import net.sf.json.JSONObject;

import com.lph.entity.Book;
import com.lph.impl.BookDaoImpl;

public class WebServiceTest extends HttpServlet {
private static final long serialVersionUID = 1L;
private List<Book> list;
private BookDaoImpl bookDaoImpl = new BookDaoImpl();

public WebServiceTest() {
super();
}

protected void doGet(HttpServletRequest request,
HttpServletResponse response) throws ServletException, IOException {
response.setCharacterEncoding("utf-8");
response.setContentType("text/plain");

PrintWriter out = response.getWriter();
JSONArray jsonArray = new JSONArray();
list = bookDaoImpl.getBooks();
for (Book book : list) {
JSONObject jsonObject = new JSONObject();
jsonObject.put("id", book.getId());
jsonObject.put("pic", book.getImage());
jsonObject.put("price", book.getPrice());
jsonObject.put("remark", book.getRemark());
jsonObject.put("author", book.getAuthor());
jsonObject.put("detail", book.getDetail());
jsonObject.put("name", book.getName());
jsonArray.add(jsonObject);
}
out.write(jsonArray.toString());
out.flush();
out.close();

}

protected void doPost(HttpServletRequest request,
HttpServletResponse response) throws ServletException, IOException {
response.setCharacterEncoding("utf-8");
response.setContentType("text/plain");

PrintWriter out = response.getWriter();
JSONArray jsonArray = new JSONArray();
list = bookDaoImpl.getBooks();
for (Book book : list) {
JSONObject jsonObject = new JSONObject();
jsonObject.put("id", book.getId());
jsonObject.put("pic", book.getImage());
jsonObject.put("price", book.getPrice());
jsonObject.put("remark", book.getRemark());
jsonObject.put("author", book.getAuthor());
jsonObject.put("detail", book.getDetail());
jsonObject.put("name", book.getName());
jsonArray.add(jsonObject);
}
out.write(jsonArray.toString());
out.flush();
out.close();

}
}</span>


web.xml

这样在浏览器上输入:http://localhost:8080/myHttpServer/WebServiceTest访问若出现如下页面即服务端搭建成功:

接下来我们来搭建Android客户端

首页我们建一个Android工程,名字因人而异,我的工程目录如下:

<span style="font-size:18px;">MainActivity.java

package com.example.androidservletdemo;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.util.ArrayList;
import java.util.List;

import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.HttpStatus;
import org.apache.http.NameValuePair;
import org.apache.http.client.ClientProtocolException;
import org.apache.http.client.HttpClient;
import org.apache.http.client.entity.UrlEncodedFormEntity;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.util.EntityUtils;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

import android.app.Activity;
import android.net.ConnectivityManager;
import android.net.NetworkInfo;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.util.Log;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.EditText;
import android.widget.Toast;

public class MainActivity extends Activity {
private EditText et_show;
private Button btn;
public static final int CONNECTION_MESSAGE_SUCCESS = 1;
public static final int CONNECTION_MESSAGE_ERROR = 2;
public static final int CONNECTION_MESSAGE_TIMEOUT = 3;

public Handler handler;
Message message = new Message();
StringBuilder sb = null;
public static final String HTTPURL = "http://192.168.65.33:8080/myHttpServer/WebServiceTest";

@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);

btn = (Button) findViewById(R.id.btn_query);
et_show = (EditText) findViewById(R.id.tv_show);

handler = new Handler() {
@Override
public void handleMessage(Message msg) {
if (msg.arg1 == CONNECTION_MESSAGE_SUCCESS) {
if (sb != null) {
parseJson(sb.toString());
}
}
}
};

btn.setOnClickListener(new OnClickListener() {

@Override
public void onClick(View v) {
Toast.makeText(MainActivity.this, "哈哈哈哈", Toast.LENGTH_LONG)
.show();
new Thread() {

@Override
public void run() {
if (checkNetWork()) {
connServerForResult(HTTPURL);
System.out
.println("=====connServerForResult(HTTPURL);==========>");
}
}
}.start();

}
});
if (checkNetWork()) {
Log.d("maiin", "工作正常");

} else {
btn.setEnabled(false);
}

}

public boolean checkNetWork() {
ConnectivityManager cm = (ConnectivityManager) this
.getSystemService(this.CONNECTIVITY_SERVICE);
NetworkInfo info = cm.getActiveNetworkInfo();
if (info != null && info.isConnected()) {
return true;
} else {
return false;
}
}

private void connServerForResult(String strUrl) {
// HttpGet对象
HttpGet httpRequest = new HttpGet(strUrl);
System.out.println("===============>" + strUrl);
try {
// HttpClient对象
HttpClient httpClient = new DefaultHttpClient();
// 获得HttpResponse对象
HttpResponse httpResponse = httpClient.execute(httpRequest);
if (httpResponse.getStatusLine().getStatusCode() == HttpStatus.SC_OK) {
// 取得返回的数据
BufferedReader reader = new BufferedReader(
new InputStreamReader(httpResponse.getEntity()
.getContent()));
sb = new StringBuilder();
String info = null;
while ((info = reader.readLine()) != null) {
sb = sb.append(info + "\n");
}

System.out.println("=================>" + sb.toString());
reader.close();
message.arg1 = CONNECTION_MESSAGE_SUCCESS;
handler.sendMessage(message);
}
} catch (ClientProtocolException e) {
et_show.setText("protocol error");
message.arg1 = CONNECTION_MESSAGE_ERROR;
handler.sendMessage(message);

} catch (IOException e) {
et_show.setText("IO error");
message.arg1 = CONNECTION_MESSAGE_ERROR;
handler.sendMessage(message);

}

}

private void parseJson(String strResult) {

StringBuffer buffer = new StringBuffer();
try {
JSONArray jsonArray = new JSONArray(strResult);
for (int i = 0; i < jsonArray.length(); i++) {
JSONObject jsonObject = jsonArray.getJSONObject(i);
buffer.append("id").append(jsonObject.getInt("id"))
.append("\n").append("name")
.append(jsonObject.getString("name")).append("\n")
.append("price").append(jsonObject.getDouble("price"))
.append("\n").append("detail")
.append(jsonObject.getString("detail")).append("\n")
.append("author")
.append(jsonObject.getString("author")).append("\n")
.append("remark").append(jsonObject.getInt("remark"))
.append("\n").append("pic")
.append(jsonObject.getString("pic"));
}

et_show.setText(buffer.toString());
} catch (JSONException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}

}
}

</span>


我在自己的手机上调试的结果如下:

第一次写博文,难免有点紧张,

有什么不妥的地方,欢迎大家批评改正!
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: