查看局域网地址
一般安卓前端通信就会涉及到网络,所以前提是把你APP运行的手机和电脑在同一个局域网中,其他方法也可以访问电脑上的服务器,笔者没有验证过,所以就介绍我的方法:
1.打开电脑的热点(前提是电脑连着网呢),然后让手机连上,这就在一个局域网了;
2.安卓端发送数据,得有后台的网络地址,所以需要查这个局域网地址是啥,下面来操作;
3.用命令行输入ipconfig语句查看无线局域网适配器的IPv4地址,如图:
这个时候这个地址就是以后安卓端发送数据给后台的目的地址了
安卓端代码实现
注意点:
1.在安卓端发送数据给后台时,因为比较耗时,所以得需要开启子线程,在子线程里发送及接受数据,但是接受完了,还得操作主线程的UI啥的,所以要用到Handler来处理一下子线程向主线程发送的信息,然后操作主线程里的数据;
2.在发送网络数据时要用到OkHttpUtils来发送数据,用google的Gson来解析后台发送过来的JSON数据,所以导入以下依赖,放在app下的builde.gradle下;
//网络解析
implementation 'com.squareup.okhttp:okhttp:2.4.0'
implementation 'com.squareup.okio:okio:1.5.0'
implementation 'com.google.code.gson:gson:2.7'
3.因为我依赖的是com.squareup.okhttp:okhttp:2.4.0,这个版本老,所以在把传输的数据加到 RequestBody 时用的是这个语句,其他语句也可,自己查
RequestBody requestBody = new FormEncodingBuilder().add("tel", tel).build();
4.我把网络发送数据简单的分装了以下工具类,很简单,就是发送时固定的流程,其中的CallBack,在这个包中com.squareup.okhttp.Callback;是个回调函数,就是用来处理安卓端发送数据成功或失败的时间的,要重写他;
import com.squareup.okhttp.Callback;
import com.squareup.okhttp.OkHttpClient;
import com.squareup.okhttp.Request;
import com.squareup.okhttp.RequestBody;
public class OkHttpUtils {
static OkHttpClient client=null;
public static void sendMessage(String url, RequestBody requestBody, Callback callback){//callback回调函数,用来处理传送回来的数据
client=new OkHttpClient();
Request request=new Request.Builder().url(url).post(requestBody).build();
client.newCall(request).enqueue(callback);
}
}
5.Gson用来处理后台发送来的JSON数据,并把它转换为自己需要的对象(或对象数组)类型,具体知识,去看课本吧
下面上代码:
//******************获取云端数据**************
public void getNotesByNet(){
//用来处理子线程发来的数据
final Handler handler=new Handler(){
@Override
public void handleMessage(Message msg) {
switch (msg.what){
case 1:
Toast.makeText(MainActivity.this,"获取云端数据成功!",Toast.LENGTH_LONG).show();
notes2=(LinkedList<Note>)msg.obj;
//把它插进数据库里
for (int i=0;i<notes2.size();i++){
//插入数据库操作,看不懂没关系,理解逻辑
dbBus.addNoteNetOrLocal(notes2.get(i),MainActivity.this,0);
}
break;
default:Toast.makeText(MainActivity.this,"获取云端数据失败!",Toast.LENGTH_LONG).show();
break;
}
}
};
//这就是访问后台的局域网地址+项目名+你的SSM框架中的controller方法,得加转义字符
String url="http:192.168.137.1:8099//MyNote//controller//queryAllByTel";
//把要传递的数据格式化成网络传输要求的格式
RequestBody requestBody = new FormEncodingBuilder().add("tel", tel).build();
OkHttpUtils.sendMessage(url, requestBody, new Callback() {//重写Callback()方法,处理成功或失败事件
@Override
public void onFailure(Request request, IOException e) {//发送失败
Message msg=new Message();
//给个发送失败的的标志给主线程
msg.what=0;
handler.sendMessage(msg);
}
@Override
public void onResponse(Response response) throws IOException {//处理发送成功
String responseData= URLDecoder.decode(response.body().string(), "utf-8");//可能编码方式不同造成乱码,所以对接受的数据加一下编码方式,写死它
Gson gson=new Gson();
//用Gson把数据转换为对象数组格式
LinkedList<Note> notes3=gson.fromJson(responseData,new TypeToken<LinkedList<Note>>(){}.getType());
Log.d("取出来的数据1:", notes3.get(0).getContent()+"************"+ notes3.get(1).getContent());
Message msg=new Message();
msg.what=1;
//把对象数组发给主线程,然后更新数据库
msg.obj=notes3;
handler.sendMessage(msg);
}
});
服务器端
注意点:
1.在安卓端访问服务器端时因为要返回数据给安卓端,所以在controller类前面要加@RestController表示这是个Response和Controller,这是给安卓端时特有的,
如果给网页返回数据时注解是@RestController,这点要注意
2.跟正常函数一样,该返回啥返回啥,没啥特殊要求,顶多给个注解
下面上代码:
package org.wang.controller;
import java.io.IOException;
import java.io.PrintWriter;
import java.io.UnsupportedEncodingException;
import java.net.URLEncoder;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.LinkedList;
import java.util.List;
import java.util.Map;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.bind.annotation.RestController;
import org.wang.entity.Note;
import org.wang.service.NoteService;
import net.sf.json.JSONArray;
import net.sf.json.JSONObject;
//访问路径对应的映射,学了SSM框架就知道了
@RequestMapping("controller")
@RestController//这需要注意和给网页返回数据的区别
public class NoteController {
//控制器依赖于service,这是Spring的依赖注入,相当于初始化一个noteService
@Autowired
@Qualifier("noteService")
private NoteService noteService;
public void setNoteService(NoteService noteService) {
this.noteService = noteService;
}
//增加数据
@RequestMapping(value = "addNote")
//注意@ResponseBody,表示返回的数据,据说不加也可以,没验证过
//@RequestParam("id") String id这是spring MVC中把传进来的参数通过注解对应起来,防止出差错,必写
public @ResponseBody String addNote(@RequestParam("id") String id,@RequestParam("content") String content,@RequestParam("groupName") String groupName,@RequestParam("createTime") String createTime,@RequestParam("title") String title,@RequestParam("subContent") String subContent,@RequestParam("tel") String tel) throws UnsupportedEncodingException{
int id1=Integer.parseInt(id);
Note note=new Note(id1, content, groupName, createTime, title, subContent, tel);
//MyBatis访问数据库的语句,理解逻辑
noteService.addNote(note);
System.out.println("注入成功");
return tel;
}
//删除数据
@RequestMapping(value = "deleteNote")
public @ResponseBody String deleteNote(@RequestParam("createTime") String createTime,@RequestParam("tel") String tel) throws UnsupportedEncodingException{
noteService.deleteNote(createTime,tel);
System.out.println("删除成功");
return "223";
}
//按照电话查询所有日记,这是返回数组的形式
@RequestMapping(value = "queryAllByTel")
public @ResponseBody LinkedList<Note> queryAllByTel(@RequestParam("tel") String tel) throws UnsupportedEncodingException{
List<Note> notes=noteService.queryAllByTel(tel);
//这是我安卓端要的数据是LinkedList类型,所以我处理了下,并不是安卓和后台交互时有啥特殊
LinkedList< Note> notes1=new LinkedList<Note>();
for(int i=0;i<notes.size();i++) {
notes1.add(notes.get(i));
}
System.out.println("查询成功");
return notes1;
}
//按照电话分组查询所有日记
@RequestMapping(value = "queryAllByGroupName")
public @ResponseBody LinkedList<Note> queryAllByGroupName(@RequestParam("groupName") String groupName,@RequestParam("tel") String tel) throws UnsupportedEncodingException{
List<Note> notes=noteService.queryAllByGroupName(groupName,tel);
LinkedList< Note> notes1=new LinkedList<Note>();
for(int i=0;i<notes.size();i++) {
notes1.add(notes.get(i));
}
System.out.println("按照电话查询成功");
return notes1;
}
//按照id查询所有便签内容
@RequestMapping(value = "getNoteContentById")
public @ResponseBody String getNoteContentById(@RequestParam("id") String id) throws UnsupportedEncodingException{
int id1=Integer.parseInt(id);
Note note=noteService.getNoteContentById(id1);
System.out.println("根据ID查询便签内容成功");
return note.getContent();
}
//按照id查询所有便签内容
@RequestMapping(value = "getNoteById")
public @ResponseBody Note getNoteById(@RequestParam("id") String id) throws UnsupportedEncodingException{
int id1=Integer.parseInt(id);
Note note=noteService.getNoteContentById(id1);
System.out.println("根据ID查询便签成功");
return note;
}
}
如果想看我整个的项目开发流程,可以参见我的源码:
安卓端链接:https://download.csdn.net/download/weixin_42504539/11287496
服务器端链接:https://download.csdn.net/download/weixin_42504539/11287523