Java服务器对外提供接口以及Android端向服务器请求数据

时间:2022-01-28 22:31:32

转载请注明出处:http://www.cnblogs.com/Joanna-Yan/p/5056780.html

讲解下java服务器是如何对移动终端提供接口的,以什么数据格式提供出去,移动端又是怎么请求服务器,接收以及解析返回数据的。

服务端:还是在原先S2SH框架的项目上(搭建SSH详细步骤及其相关说明),加入Servlet来做对终端提供接口的事情。

Android端:用了一个网络访问框架okHttp,向服务器请求数据。

服务端:

servlet接收移动端的get、post请求,进行相应逻辑处理后将要返回的数据封装成json格式写出去。

对数据库的操作传统的Servlet是用jdbc,但是操作过于繁琐,这里重用项目中的Hibernate。那么如何在Servlet中使用Hibernate呢?

Servlet是定义在web.xml中,在Servlet类中用new ClassPathXmlApplicationContext("applicationContext.xml");就可以得到Spring容器,从而可以取到Hibernate来操作数据库了。

ApplicationContext ac=new ClassPathXmlApplicationContext("applicationContext.xml");
UserDAO userDAO=(UserDAO) ac.getBean("UserDAO");
List<User> userList=userDAO.findAll();

在使用Json时,必须要导入的jar:

commons-beanutils-1.7.0.jar

commons-collections-3.2.1.jar

commons-httpclient-3.1.jar

commons-lang-2.3.jar

commons-logging-1.1.1.jar

ezmorph-1.0.3.jar

json-lib-2.2.3-jdk15.jar

UserServlet.java

package joanna.yan.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 joanna.yan.dao.UserDAO;
import joanna.yan.entity.User;
import net.sf.json.JSONArray;
import net.sf.json.JSONObject;
import org.springframework.context.ApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext; public class UserServlet extends HttpServlet{
@Override
protected void doGet(HttpServletRequest req, HttpServletResponse resp)
throws ServletException, IOException {
doPost(req, resp);
} @Override
protected void doPost(HttpServletRequest req, HttpServletResponse resp)
throws ServletException, IOException {
System.out.println("被访问了!");
PrintWriter out=resp.getWriter();
JSONObject json=new JSONObject();
JSONObject json1=new JSONObject();
String msg="success";
int errorcode=0;
ApplicationContext ac=new ClassPathXmlApplicationContext("applicationContext.xml");
try {
UserDAO userDAO=(UserDAO) ac.getBean("UserDAO");
List<User> userList=userDAO.findAll();
if(userList.size()>0){
JSONArray jsonArray=new JSONArray();
for (User user : userList) {
json1.put("id", user.getId());
json1.put("username", user.getUsername());
json1.put("age", user.getUsername());
jsonArray.add(json1);
}
json.put("data", jsonArray);
}else{
msg="没有符合要求的数据";
errorcode=1;
json.put("data", "");
}
} catch (Exception e) {
e.printStackTrace();
msg = "系统错误";
errorcode = 10000;
}finally{
json.put("message", msg);
json.put("errorcode", errorcode);
out.print(json);
out.flush();
out.close();
}
}
}

在web.xml中配置UserServlet

 <servlet>
<servlet-name>userServlet</servlet-name>
<servlet-class>joanna.yan.servlet.UserServlet</servlet-class>
</servlet>
<servlet-mapping>
<servlet-name>userServlet</servlet-name>
<url-pattern>/user</url-pattern>
</servlet-mapping>

Android端:

使用okhttp,在官网下载okhttp-2.7.0.jar和okio-1.6.0.jar放入libs下,并Add Build Path。同时添加解析json数据的gson-2.2.4.jar

MainActivity.java

package com.example.commussh;

import java.io.IOException;
import java.util.Map;
import android.app.Activity;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import android.widget.TextView;
import com.google.gson.Gson;
import com.squareup.okhttp.OkHttpClient;
import com.squareup.okhttp.Request;
import com.squareup.okhttp.Response; public class MainActivity extends Activity {
TextView tv_show;
Button btn_search;
OkHttpClient client;
Gson gson;
static class Gist {
Map<String, GistFile> files;
}
static class GistFile {
String content;
} @Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main); client= new OkHttpClient();
gson=new Gson();
tv_show=(TextView) findViewById(R.id.tv_show);
btn_search=(Button) findViewById(R.id.btn_search);
btn_search.setOnClickListener(new View.OnClickListener() { @Override
public void onClick(View v) {
new Thread(new Runnable() { @Override
public void run() {
Request request = new Request.Builder()
.url("http://localhost:8080/SSH/user")
.build();
Response response;
try {
response = client.newCall(request).execute();
if (!response.isSuccessful()) throw new IOException("Unexpected code: " + response);
Gist gist = gson.fromJson(response.body().charStream(), Gist.class);
for (Map.Entry<String, GistFile> entry : gist.files.entrySet()) {
System.out.println(entry.getKey());
System.out.println(entry.getValue().content);
}
} catch (IOException e) {
e.printStackTrace();
}
}
}).start();
}
});
}
}

测试结果:

Java服务器对外提供接口以及Android端向服务器请求数据

源码:http://pan.baidu.com/s/1mgU7xKs   提取码:pe9i

如果此文对您有帮助,微信打赏我一下吧~

Java服务器对外提供接口以及Android端向服务器请求数据