利用Volley框架实现简单的Android与servlet信息交互
写这篇文章之前,我参考了这篇帖子内容https://blog.csdn.net/Mr_Megamind/article/details/74048891
先来进行servlet服务器的搭建
这里我就实现简单的获取来自客户端的信息,并返回一些信息
直接上代码:
package serverlet;
import java.io.IOException;
import java.io.PrintWriter;
import java.util.HashMap;
import java.util.Map;
import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import net.sf.json.JSONObject;
/**
* Servlet implementation class net
*/
@WebServlet("/net")
public class net extends HttpServlet {
private static final long serialVersionUID = 1L;
/**
* @see HttpServlet#HttpServlet()
*/
public net() {
super();
// TODO Auto-generated constructor stub
}
/**
* @see HttpServlet#doGet(HttpServletRequest request, HttpServletResponse response)
*/
protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
// TODO Auto-generated method stub
response.setCharacterEncoding("utf-8"); //设置 HttpServletResponse使用utf-8编码
response.setHeader("Content-Type", "text/html;charset=utf-8"); //通知浏览器使用utf-8解码
response.getWriter().append("Served at: ").append(request.getContextPath());
request.setCharacterEncoding("utf-8");
try (PrintWriter out = response.getWriter()) {
//获得请求中传来的用户名和密码
String accountNumber = request.getParameter("AccountNumber");
String password = request.getParameter("Password");
String s=accountNumber+password;
System.out.println(s);
Map<String, String> params = new HashMap<>();
JSONObject jsonObject = new JSONObject();
params.put("Result",s);
jsonObject.put("params",params);
System.out.println(jsonObject.toString());
response.resetBuffer();//清空原有的输出流,方便客户端获取到json字符串
out.write(jsonObject.toString());//将json字符串写入输出流
}
}
/**
* @see HttpServlet#doPost(HttpServletRequest request, HttpServletResponse response)
*/
protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
// TODO Auto-generated method stub
doGet(request, response);
}
}
接下来是客户端的代码
使用Volley首先要在项目中添加Volley.jar包
接下来是使用步骤
1.创建RequestQuene对象,定义网络请求队列;
2.创建**Request对象,**代表String、JSON、Image用于定义网络请求的接收,这里我使用的是StringRequest;
3.把**Request请求对象添加到RequestQuene对象中,开始执行网络请求;
4.在AndroidManifest中注册,添加网络权限;
这里先附上添加网络权限的语句:
<uses-permission android:name="android.permission.INTERNET" />
然后是app内进行网络请求的函数体的代码
public void LoginRequest(final String accountNumber, final String password) { //请求地址 String url = "http://域名:端口号/MyFirstWebApp/LoginServlet"; String tag = "Login"; //取得请求队列 RequestQueue requestQueue = Volley.newRequestQueue(getApplicationContext()); //防止重复请求,先取消tag标识的请求队列 requestQueue.cancelAll(tag); //创建StringRequest,定义字符串请求的请求方式为POST(省略第一个参数会默认为GET方式) final StringRequest request = new StringRequest(Request.Method.POST, url, new Response.Listener<String>() { @Override public void onResponse(String response) { try { //将传回的字符串转化为JSONObject JSONObject jsonObject = (JSONObject) new JSONObject(response).get("params"); String result = jsonObject.getString("Result"); //result的值就是servlet传回的result的值,对应的就是servlet中s的值 text.setText(result);//这部分内容是对返回信息的使用,text是一个Textview } catch (JSONException e) { //请求异常操作 Toast.makeText(MainActivity.this.getApplicationContext(),"无网络",Toast.LENGTH_SHORT).show(); } } }, new Response.ErrorListener() { @Override public void onErrorResponse(VolleyError error) { //响应错误操作 Toast.makeText(MainActivity.this.getApplicationContext(),"响应错误",Toast.LENGTH_SHORT).show(); } }) { @Override protected Map<String, String> getParams() throws AuthFailureError { Map<String, String> params = new HashMap<>(); params.put("AccountNumber", accountNumber); //注⑥ params.put("Password", password); return params; } }; //设置Tag标签 request.setTag(tag); //将请求添加到队列中 requestQueue.add(request); } @Override protected Response<String> parseNetworkResponse(NetworkResponse response) { String str = null; try { str = new String(response.data, "utf-8"); } catch (UnsupportedEncodingException e) { e.printStackTrace(); } return Response.success(str, HttpHeaderParser.parseCacheHeaders(response)); } }

浙公网安备 33010602011771号