android通过POST和GET两种方式发送数据到web应用实战 博客分类: android项目实践 POST、GET
一、web应用端
1、servlet
package com.caiz.web.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 AcceptServelet
*/
@WebServlet("/AcceptServelet")
public class AcceptServelet extends HttpServlet {
private static final long serialVersionUID = 1L;
/**
* @see HttpServlet#doGet(HttpServletRequest request, HttpServletResponse
* response)
*/
protected void doGet(HttpServletRequest request,
HttpServletResponse response) throws ServletException, IOException {
String title = request.getParameter("title");
String id = request.getParameter("id");
System.out.println("method=" + request.getMethod());
System.out.println("id=" + id);
System.out.println("title=" + title);
}
/**
* @see HttpServlet#doPost(HttpServletRequest request, HttpServletResponse
* response)
*/
protected void doPost(HttpServletRequest request,
HttpServletResponse response) throws ServletException, IOException {
this.doGet(request, response);
}
}
2、filter,用于乱码处理
a、过滤器filter
package com.caiz.web.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;
/**
* 参数编码处理过滤器
* @author HuangYucai
*/
@WebFilter("/*")
public class EncodingFilter implements Filter {
/**
* Default constructor.
*/
public EncodingFilter() {
}
/**
* @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 {
HttpServletRequest req = (HttpServletRequest) request;
if ("GET".equals(req.getMethod())) {
EncodedHttpServletRequest warpper = new EncodedHttpServletRequest(
req);
chain.doFilter(warpper, 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
}
}
b、包装request类
package com.caiz.web.filter;
import java.io.UnsupportedEncodingException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletRequestWrapper;
/**
* request的参数编码出来
* @author HuangYucai
*
*/
public class EncodedHttpServletRequest extends HttpServletRequestWrapper {
private HttpServletRequest request;
public EncodedHttpServletRequest(HttpServletRequest request) {
super(request);
this.request = request;
}
@Override
public String getParameter(String name) {
String value=request.getParameter(name);
if(value!=null){
try {
value=new String(value.getBytes("ISO8859-1"),"UTF-8");
} catch (UnsupportedEncodingException e) {
}
}
return value;
}
}
二、android应用端
1、主程序类:Activity
package com.caiz.android.htmlviewer;
import com.caiz.android.htmlviewer.service.PageService;
import android.app.Activity;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.TextView;
import android.widget.Toast;
/**
* 主程序类
* @author HuangYucai
*/
public class HtmlViewerActivity extends Activity {
/** Called when the activity is first created. */
private EditText pathText;
private Button viewBnt;
private TextView txtViewer;
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
pathText= (EditText)this.findViewById(R.id.path);
viewBnt=(Button)this.findViewById(R.id.bnt);
txtViewer=(TextView)this.findViewById(R.id.viewer);
viewBnt.setOnClickListener(new BntOnclickListener());
}
public final class BntOnclickListener implements View.OnClickListener{
public void onClick(View v) {
String path=pathText.getText().toString();
String html;
try {//获取字符数据设置到TextView空间
html = PageService.getPageStr(path);
txtViewer.setText(html);
} catch (Exception e) {
e.printStackTrace();
Toast.makeText(getApplicationContext(), "获取网页失败", Toast.LENGTH_SHORT).show();
}
}
}
}
2、业务类service
package com.caiz.httpreq.service;
import java.io.OutputStream;
import java.net.HttpURLConnection;
import java.net.URL;
import java.net.URLEncoder;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import org.apache.http.HttpResponse;
import org.apache.http.NameValuePair;
import org.apache.http.client.entity.UrlEncodedFormEntity;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.message.BasicNameValuePair;
/**
* Android发送数据到web的业务类
* @author HuangYucai
*
*/
public class HttpSendService {
// 通过GET方法提交数据
public boolean saveByGetMethod(int id, String title) throws Exception {
String path = "http://192.168.0.186:8080/web/AcceptServelet";
// 构造参数的Map
HashMap<String, String> params = new HashMap<String, String>();
params.put("id", String.valueOf(id));
params.put("title", title);
// 发送GET请求
return sendHttpClientRequest(path, params,"UTF-8");
}
// 通过HttpClient请求的方法
public boolean sendHttpClientRequest(String path, Map<String, String> params,String charsetName)
throws Exception {
// 设置请求参数的名值对
List<NameValuePair> pairList=new ArrayList<NameValuePair>();
for (Map.Entry<String, String> entry : params.entrySet()) {
pairList.add(new BasicNameValuePair(entry.getKey(),entry.getValue()));
}
UrlEncodedFormEntity entity=new UrlEncodedFormEntity(pairList,charsetName);//创建请求的url实体
HttpPost httpPost=new HttpPost(path);//创建http请求实例
httpPost.setEntity(entity);
DefaultHttpClient client=new DefaultHttpClient();// 实例化请求客户端
HttpResponse response=client.execute(httpPost);// 执行请求
if(response.getStatusLine().getStatusCode()==200){// 请求成功
return true;
}
return false;
}
// 发送GET请求的方法
public boolean sendGetRequest(String path, Map<String, String> params,String charsetName)
throws Exception {
// 拼接带参数的请求路径
StringBuilder url = new StringBuilder(path);
url.append("?");
for (Map.Entry<String, String> entry : params.entrySet()) {
url.append(entry.getKey()).append("=")
.append(URLEncoder.encode(entry.getValue(),charsetName))
.append("&");
}
url.deleteCharAt(url.length() - 1);
// 发送请求
HttpURLConnection conn = (HttpURLConnection) (new URL(url.toString())
.openConnection());
conn.setRequestMethod("GET");
conn.setConnectTimeout(5000);
if (conn.getResponseCode() == 200) {//如果发送成功
return true;
}
return false;
}
// 发送Post请求的方法
public boolean sendPostRequest(String path, Map<String, String> params,String charsetName)
throws Exception {
// 拼接带参数的请求路径
StringBuilder data = new StringBuilder("");
for (Map.Entry<String, String> entry : params.entrySet()) {
data.append(entry.getKey()).append("=")
.append(URLEncoder.encode(entry.getValue(),charsetName))
.append("&");
}
data.deleteCharAt(data.length() - 1);
byte[] dataBytes=data.toString().getBytes();
// 发送请求
HttpURLConnection conn = (HttpURLConnection) (new URL(path.toString()).openConnection());
conn.setRequestMethod("POST");
conn.setConnectTimeout(5000);
conn.setDoOutput(true);//设置可以输出数据
//设置内容类型
conn.setRequestProperty("Content-Type", "application/x-www-form-urlencoded");
//设置内容长度
conn.setRequestProperty("Content-Length", String.valueOf(dataBytes.length));
OutputStream outStream =conn.getOutputStream();
outStream.write(dataBytes);
if (conn.getResponseCode() == 200) {//如果发送成功
return true;
}
return false;
}
}
3、在主配置文件Androidmanifset.xml配置访问网络的权限
<uses-permission android:name="android.permission.INTERNET"/>
上一篇: Java面试资料