Android网络编程之传递数据给服务器(一)
请尊重他人的劳动成果,转载请注明出处:Android网络编程之传递数据给服务器(一)
因为Android程序需要和服务器进行通信,所以需要服务器端提供的支持。
通过GET方式上传数据主要适用于数据大小不超过2KB,且对安全性要求不高的情况下。
服务器端项目结构:
package com.jph.sgm.servlet;
import java.io.IOException;
import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
/**
* Servlet implementation class ServletForGETMethod
*/
@WebServlet("/ServletForGETMethod")
public class ServletForGETMethod extends HttpServlet {
private static final long serialVersionUID = 1L;
/**
* @see HttpServlet#HttpServlet()
*/
public ServletForGETMethod() {
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
//获取请求的参数(使用utf-8进行解码,然后用进行ISO8859-1编码)
// String name=new String(request.getParameter("name").getBytes("ISO8859-1"),"utf-8");
String name=request.getParameter("name");
String pwd=request.getParameter("pwd");
System.out.println("name:"+name+" pwd:"+pwd);
}
/**
* @see HttpServlet#doPost(HttpServletRequest request, HttpServletResponse response)
*/
protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
// TODO Auto-generated method stub
}
}
发布项目并在浏览器中输入:http://localhost:8080/ServerForGETMethod/ServletForGETMethod?name=aa&pwd=124
可以再控制台看到如下图的输出:
至此服务器端项目已经完成。下面开始创建Android端项目。
Android端项目结构:
核心代码:SendDateToServer.java:
package com.jph.sdg.service;
import java.net.HttpURLConnection;
import java.net.URL;
import java.net.URLEncoder;
import java.util.HashMap;
import java.util.Map;
import android.os.Handler;
/**
* 通过GET方式向服务器发送数据
* @author jph
* Date:2014.09.27
*/
public class SendDateToServer {
private static String url="http://10.219.61.117:8080/ServerForGETMethod/ServletForGETMethod";
public static final int SEND_SUCCESS=0x123;
public static final int SEND_FAIL=0x124;
private Handler handler;
public SendDateToServer(Handler handler) {
// TODO Auto-generated constructor stub
this.handler=handler;
}
/**
* 通过Get方式向服务器发送数据
* @param name 用户名
* @param pwd 密码
*/
public void SendDataToServer(String name,String pwd) {
// TODO Auto-generated method stub
final Mapmap=new HashMap();
map.put("name", name);
map.put("pwd", pwd);
new Thread(new Runnable() {
@Override
public void run() {
// TODO Auto-generated method stub
try {
if (sendGetRequest(map,url,"utf-8")) {
handler.sendEmptyMessage(SEND_SUCCESS);//通知主线程数据发送成功
}else {
//将数据发送给服务器失败
}
} catch (Exception e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}).start();
}
/**
* 发送GET请求
* @param map 请求参数
* @param url 请求路径
* @return
* @throws Exception
*/
private boolean sendGetRequest(Map param, String url,String encoding) throws Exception {
// TODO Auto-generated method stub
//http://localhost:8080/ServerForGETMethod/ServletForGETMethod?name=aa&pwd=124
StringBuffer sb=new StringBuffer(url);
if (!url.equals("")&!param.isEmpty()) {
sb.append("?");
for (Map.Entryentry:param.entrySet()) {
sb.append(entry.getKey()+"=");
sb.append(URLEncoder.encode(entry.getValue(), encoding));
sb.append("&");
}
sb.deleteCharAt(sb.length()-1);//删除字符串最后 一个字符“&”
}
HttpURLConnection conn=(HttpURLConnection) new URL(sb.toString()).openConnection();
conn.setConnectTimeout(5000);
conn.setRequestMethod("GET");//设置请求方式为GET
if (conn.getResponseCode()==200) {
return true;
}
return false;
}
}
package com.jph.sdg.activity;
import com.jph.sdg.R;
import com.jph.sdg.service.SendDateToServer;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.app.Activity;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.EditText;
import android.widget.Toast;
/**
* 通过GET方式向服务器发送数据,通过GET方式上传数据主要适用于数
* 据大小不超过2KB,且对安全性要求不高的情况下。
* @author jph
* Date:2014.09.27
*/
public class MainActivity extends Activity {
private EditText edtName,edtPwd;
private Button btnSend;
Handler handler=new Handler(){
public void handleMessage(Message msg) {
switch (msg.what) {
case SendDateToServer.SEND_SUCCESS:
Toast.makeText(MainActivity.this, "登陆成功", Toast.LENGTH_SHORT).show();
break;
case SendDateToServer.SEND_FAIL:
Toast.makeText(MainActivity.this, "登陆失败", Toast.LENGTH_SHORT).show();
break;
default:
break;
}
};
};
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
edtName=(EditText)findViewById(R.id.edtName);
edtPwd=(EditText)findViewById(R.id.edtPwd);
btnSend=(Button)findViewById(R.id.btnSend);
btnSend.setOnClickListener(new OnClickListener() {
@Override
public void onClick(View v) {
// TODO Auto-generated method stub
String name=edtName.getText().toString();
String pwd=edtPwd.getText().toString();
if (edtName.equals("")||edtPwd.equals("")) {
Toast.makeText(MainActivity.this, "用户名或密码不能为空", Toast.LENGTH_LONG).show();
}else {
new SendDateToServer(handler).SendDataToServer(name, pwd);
}
}
});
}
}
至此Android端项目已经完成了。下面就让我们看一下APP运行效果吧:
Android运行效果图:
2
当客户端向服务器发送中文时服务器端会出现乱码现象,如下图:
出现乱码的原因主要是,Android客户端我们采用的是UTF-8编码,而Tomcat默认采用的是ISO8859-1编码,所以会出现中文乱码的现象。
解决方案有两种:
是使用UTF-8解码请求参数得到汉字,然后再通过ISO8859-1进行编码。此时服务器端的Servlet是:
package com.jph.sgm.servlet;
import java.io.IOException;
import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
/**
* Servlet implementation class ServletForGETMethod
*/
@WebServlet("/ServletForGETMethod")
public class ServletForGETMethod extends HttpServlet {
private static final long serialVersionUID = 1L;
/**
* @see HttpServlet#HttpServlet()
*/
public ServletForGETMethod() {
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
//获取请求的参数(使用utf-8进行解码,然后用进行ISO8859-1编码)
String name=new String(request.getParameter("name").getBytes("ISO8859-1"),"utf-8");
// String name=request.getParameter("name");
String pwd=request.getParameter("pwd");
System.out.println("name:"+name+" pwd:"+pwd);
}
/**
* @see HttpServlet#doPost(HttpServletRequest request, HttpServletResponse response)
*/
protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
// TODO Auto-generated method stub
}
}
运行结果如下图:
下面我们采用过滤器的方式来解决乱码的问题:
第一步:建立一个Filter过滤器。
EncodingFilter.java
package com.jph.sgm.filter;
import java.io.IOException;
import javax.servlet.Filter;
import javax.servlet.FilterChain;
import javax.servlet.FilterConfig;
import javax.servlet.ServletException;
import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;
import javax.servlet.annotation.WebFilter;
import javax.servlet.http.HttpServletRequest;
/**
* Servlet Filter implementation class EncodingFilter
*/
@WebFilter("/*")
public class EncodingFilter implements Filter {
/**
* Default constructor.
*/
public EncodingFilter() {
// TODO Auto-generated constructor stub
}
/**
* @see Filter#destroy()
*/
public void destroy() {
// TODO Auto-generated method stub
}
/**
* @see Filter#doFilter(ServletRequest, ServletResponse, FilterChain)
*/
public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain) throws IOException, ServletException {
// TODO Auto-generated method stub
HttpServletRequest req=(HttpServletRequest) request;
if ("GET".equals(req.getMethod())) {
HttpServletRequestEncodingWrapper wrapper=new HttpServletRequestEncodingWrapper(req);
chain.doFilter(wrapper, response);
}else {
req.setCharacterEncoding("utf-8");
chain.doFilter(request, response);
}
}
/**
* @see Filter#init(FilterConfig)
*/
public void init(FilterConfig fConfig) throws ServletException {
// TODO Auto-generated method stub
}
}
上面的过滤器因为设置了过滤路径为*/所以会过滤所有的Servlet。
在上面的过滤器中用到了一个包装器,HttpServletRequestEncodingWrapper.java
package com.jph.sgm.filter;
import java.io.UnsupportedEncodingException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletRequestWrapper;
public class HttpServletRequestEncodingWrapper extends
HttpServletRequestWrapper {
private HttpServletRequest request;
public HttpServletRequestEncodingWrapper(HttpServletRequest request) {
// TODO Auto-generated constructor stub
super(request);
this.request=request;
}
@Override
public String getParameter(String name) {
// TODO Auto-generated method stub
String value=request.getParameter(name);
if (value!=null) {
try {//用utf-8进行解码,然后用ISO8859-1进行编码
return new String(value.getBytes("ISO8859-1"),"utf-8");
} catch (UnsupportedEncodingException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
return super.getParameter(name);
}
}
重新运行项目可以看到服务器会将客户端发来的数据用UTF-8进行解码,用ISO8859-1进行编码。运行效果图如下:
Android网络编程之传递数据给服务器(二)——通过POST的方式将数据传递给服务器