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( ...
随机推荐
- linux 多线程基础
参考出处:http://www.cnblogs.com/skynet/archive/2010/10/30/1865267.html 1.进程与线程 进程是程序代码在系统中的具体实现.进程是拥有所需资 ...
- 配置Spark on YARN集群内存
参考原文:http://blog.javachen.com/2015/06/09/memory-in-spark-on-yarn.html?utm_source=tuicool 运行文件有几个G大,默 ...
- (原).NET程序加入多语言包解决方案工具,超级棒
Multi-Language Add-In Version 5.04.0088 for Visual Studio 2013 安装包:http://www.jollans.com/SetupMulti ...
- SQL Server 2012基本知识
1:图形化界面设置外键 解决:table->选中表->design->选中需要设置外键的字段->选择"关系"->选择"添加"-&g ...
- 如何识别一个字符串是否Json格式
前言: 距离上一篇文章,又过去一个多月了,近些时间,工作依旧很忙碌,除了管理方面的事,代码方面主要折腾三个事: 1:开发框架(一整套基于配置型的开发体系框架) 2:CYQ.Data 数据层框架(持续的 ...
- .NET Fringe 定义未来
在dotnetconf 2015会宣布了4.12-14 在波特兰召开 .NET Fringe http://dotnetfringe.org/ ,中文社区很少有相关的介绍,本文向大家介绍下这个.NET ...
- Mac OS X上IntelliJ IDEA 13与Tomcat 8的Java Web开发环境搭建
这标题实在有点拗口,不知道怎么写好,但看了标题也就明白文本的内容.最近几天在折腾这些玩意儿,所以写写总结.除了环境搭建,本文还是一篇入门级的上手教程. 去下载一些东西 JDK安装 Tomcat安装 T ...
- 探索C#之虚拟桶分片
阅读目录 背景 虚拟桶(virtual buckets) 实现 总结 背景 关于数据分片讨论最多的是一致性hash,然而它并不是分布式设计中的银弹百试百灵. 在数据稳定性要求比较高的场景下它的缺点是不 ...
- java中文乱码解决之道(三)-----编码详情:伟大的创想---Unicode编码
随着计算机的发展.普及,世界各国为了适应本国的语言和字符都会自己设计一套自己的编码风格,正是由于这种乱,导致存在很多种编码方式,以至于同一个二进制数字可能会被解释成不同的符号.为了解决这种不兼容的问题 ...
- VBA批量查找和复制文件
Function findAndCopy(srcFile As String, destFile As String, cmdFile As String) Dim WSH As Object, wE ...