Java服务器对外提供接口以及Android端向服务器请求数据
转载请注明出处: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();
}
});
}
}
测试结果:

源码:http://pan.baidu.com/s/1mgU7xKs 提取码:pe9i
如果此文对您有帮助,微信打赏我一下吧~

Java服务器对外提供接口以及Android端向服务器请求数据的更多相关文章
- 开发FTP服务接口,对外提供接口服务
注意:本文只适合小文本文件的上传下载,因为post请求是有大小限制的.默认大小是2m,虽然具体数值可以调节,但不适合做大文件的传输 最近公司有这么个需求:以后所有的项目开发中需要使用ftp服务器的地方 ...
- Frp内网穿透搭建,家庭主机对外提供接口,支持ssh访问
Frp内网穿透搭建,家庭主机对外提供接口,支持ssh访问 1.使用场景: 需求1.家中服务器 ubuntu 主机,跑接口服务,需要对外暴漏, 需求2.同时需要在外网ssh远程 关键词: frp内网 ...
- 使用WCF对外提供接口
本篇将通过WCF以webservices的方式对外提供接口.同时使用NUnit对webservices中的方法进行单元测试. 开发契约 contract Contract项目为类库项目,该项目下会包含 ...
- springboot+CXF开发webservice对外提供接口(转)
文章来源:http://www.leftso.com/blog/144.html 1.项目要对外提供接口,用webservcie的方式实现 2.添加的jar包 maven: <dependenc ...
- java攻城狮之路(Android篇)--与服务器交互
一.图片查看器和网页源码查看器 在输入地址的是不能输入127.0.0.1 或者是 localhost.ScrollView :可以看成一个滚轴 可以去包裹很多的控件在里面 练习1(图片查看器): pa ...
- vue 对象提供的属性功能、通过axio请求数据(2)
1 Vue对象提供的属性功能 1.1 过滤器 过滤器,就是vue允许开发者自定义的文本格式化函数,可以使用在两个地方:输出内容和操作数据中. 1.1.1 使用Vue.filter()进行全局定义(全局 ...
- c# .NET RSA结合AES加密服务端和客户端请求数据
这几天空闲时间就想研究一下加密,环境是web程序,通过js请求后台返回数据,我想做的事js在发送请求前将数据加密,服务端收到后解密,待服务端处理完请求后,将处理结果加密返回给客户端,客户端在解密,于是 ...
- WPF内嵌WCF服务对外提供接口
要测试本帖子代码请记得管理员权限运行vs. 我写这个帖子的初衷是在我做surface小车的时候有类似的需求,感觉这个功能还挺有意思的,所以就分享给大家,网上有很多关于wcf的文章 我就不一一列举了.公 ...
- android端从服务器抓取的几种常见的数据的处理方式
1.图片 public void look(View v) { String path = et_path.getText().toString(); try { URL url = new URL( ...
随机推荐
- notepad++崩溃后文件内容变为NUL的解决方法
毫无疑问,notepad++是一款非常优秀的文本编辑器,但是notepad++有时候会崩溃,之后文件内容就会全部变成NUL 当你打文件看到自己辛辛苦苦的成果全都变成NUL是不是有想哭的感觉?" ...
- Unity自动寻路Navmesh之入门
实例 我们要实现一个功能:点击场景中的一个位置,角色可以自动寻路过去.角色会绕过各种复杂的障碍,找到一条理论上”最短路径“. 步骤 1.创建地形 2.添加角色 3.创建多个障碍物,尽量摆的复杂一点,来 ...
- 构建 Android 应用程序一定要绕过的 30 个坑
原文地址:Building Android Apps - 30 things that experience made me learn the hard way 原文作者:César Ferreir ...
- H5+Mui文件配置 vue-resource基本使用方法
使用HBuilder空项目搭建h5原生开发框架需要的文件配置: *css:mui.min.css *fonts:mui.ttf mui-icon-extra.ttf *js:mui.js mui.mi ...
- while(cin.eof)出错 poj
zoj遇到c++如何判定输入流结尾的问题,一不小心就超时了 楼下的代码可以通过zoj #include<iostream> using namespace std; int main(){ ...
- Concurrency并发性
今天看了有关性能的文章,性能也是客户所看重的. 文章推荐看了软件编程并发性. 就按书上敲了网址看:http://www.gotw.ca/publications/concurrency-ddj.htm ...
- AngularJS SPA Template For Visual Studio
单页面应用程序(SPA)[使用JavaScript.CSS和HTML强大的功能,可以构建一个单页面应用程序(SPAs)],它提供了丰富的用户体验页面.导航技术和AJAX提供必要的功能,而不用重新加载页 ...
- 跟vczh看实例学编译原理——一:Tinymoe的设计哲学
自从<序>胡扯了快一个月之后,终于迎来了正片.之所以系列文章叫<看实例学编译原理>,是因为整个系列会通过带大家一步一步实现Tinymoe的过程,来介绍编译原理的一些知识点. 但 ...
- K-均值聚类算法
K-均值聚类算法 聚类是一种无监督的学习算法,它将相似的数据归纳到同一簇中.K-均值是因为它可以按照k个不同的簇来分类,并且不同的簇中心采用簇中所含的均值计算而成. K-均值算法 算法思想 K-均值是 ...
- 七天学会ASP.NET MVC (四)——用户授权认证问题
小编应各位的要求,快马加鞭,马不停蹄的终于:七天学会 Asp.Net MVC 第四篇出炉,在第四天的学习中,我们主要了学习如何在MVC中如何实现认证授权等问题,本节主要讲了验证错误时的错误值,客户端验 ...