首页 > 代码库 > Android 通过GET和POST方式提交参数给web应用

Android 通过GET和POST方式提交参数给web应用

如何把数据上传到web应用
应用界面:
视频名称:title
时长:timelength
保存,点击保存按钮提交到web应用中,web应用中开发Manageservlet来接收数据。
get方式
服务端:
public class ManageServlet extends HttpServlet
{
  private static final long serialVersionUID = 1L;
  protected void doGet(HttpServletRequest request,HttpServletResponse response) throws ServletException,IOExceptionprotected void doGet(HttpServletRequest request,HttpServletResponse response) throws ServletException,IOException
  {
    String title = request.getParameter("title");
title =  new String(title.getBytes("ISO8859-1"),"UTF-8");
String timelength = request.getParameter("timelength");
System.out.println("视频名称:"+title);
System.out.println("时长:"+timelength);
  }
  protected void doPost(HttpServletRequest request,HttpServletResponse response) throws ServletException,IOException
  {
    
  }
}


Android端
public class MainActivity extends Activity
{
  private EditText titleText;
  private EditText lengthText;
  public void onCreate(Bundle savedInstance)
  {
     super.onCreate(Bundle savedInstance);
setContentView(R.layout.main);
titleText =(EditText)this.findViewById(R.id.title);
lengthText =(EditText)this.findViewById(R.id.timelength);
     Button saveButton=(Button) this.findViewById(R.id.button); 
     saveButton.setOnClickListener(new ButtonClickListener());
   }
   private static class ButtonClickListener implements View.OnClickListener
   {
     public void onClick(View v)
{
  String title = titleText.getText().toString();
  String length = lengthText.getText().toString();
  boolean result = NewsService.save(title,length);
  if(result)
  {
    Toast.makeText(getApplicationContext(),R.string.success,1).show();
  }else{
    Toast.makeText(getApplicationContext(),R.string.error,1).show();
  }
}
   }
}


/*保存数据*/
数据通过HTTP协议提交到网络上的web应用get post提交参数,对于2K以下的数据都可以,2K以上的必须使用post。使用get方法需要把参数把附加在路径上




public class NewsService
{
  public static boolean save(String title,String length)
  {
    String path = "http://192.168.1.100:8080/web/ManageServlet";
Map<String,String> params = new HashMap<String,String>();
params.put(("title",title);
params.put("timelength",length);
try
{
return sendGETRequest(path,params,"UTF-8");
} catch(Exception e)
{
 e.printStackTrace();
}
return false;
  }
  /*发送get请求*/
  private static boolean sendGETRequest(String path,Map<String , String> params,String ecoding) throws Exception
  {
    //http://192.168.1.100:8080/web/ManageServlet?title=xxx&timelength=90
StringBuilder url=new StringBuilder(path);
url.append("?");
for(Map.Entry<String,String> entry:params.entrySet())    //迭代集合每一个元素
    {
 url.append(entry.getKey()).append("=");
 url.append(URLEncoder.encode(entry.getValue(),ecoding));
 url.append("&");

url.deleteCharAt(url.length()-1);
HttpURLConnection conn = (HttpURLConnection)new URL(url.toString()).openConnection();
conn.setConnectTimeout(5000);
conn.setRequestMethod("GET");
if(conn.getResponseCode() == 200)
{
 return true;
}
return false;
 }
}  
提交中文的话产生乱码,产生乱码的原因:
1,在提交参数时,没有对中文参数进行URL编码
修改 url.append(entry.getValue); 
2,Tomcat服务器默认采用的是ISO8859-1编码得到参数值
服务端添加 title =  new String(title.getBytes("ISO8859-1"),"UTF-8");


如果很多参数,转换很麻烦,可以采用过滤器,不用进行转码了
新建filter:EncodingFilter
对所有路径进行过滤,可以修改URL Pattern /Servlet Name为 /*
public class EncodingFilter implements Filter
{
  public void destroy()  {}
  public void doFilter(ServletRequest request,ServletResponse response,FilterChain chain)throws IOException   //每次请求到来的时候会调用该方法
  {
    HttpServletRequest req=(HttpServletRequest) request;
 if("GET".equals(req.getMethod()))
 {
   EncodingHttpServletRequest wrapper = new EncodingHttpServletRequest(req);
chain.doFilter(wrapper,response);
 } else {
   req.setCharacterEncoding("UTF-8");
chain.doFilter(request, response);
 }
  
   
  }
  public void init(FilterConfig fConfig) thhrows ServletException{}
  
}
新建类 EncodingHttpServletRequest 
public class EncodingHttpServletRequest extends HttpServletRequestWrapper
{
  private HttpServletRequest request;
  public EncodingHttpServletRequest(HttpServletRequest request)
  {
    super(request);
this.request=request;
  }
  //勾选重写getParameter方法 @Override
  public String getParameter(String name)
  {
    String value = http://www.mamicode.com/request.getParameter(name);
if(value !=null)
{
 try{
 value = http://www.mamicode.com/new String(value.getBytes("ISO8859-1"),"UTF-8");
 } catch (UnsupportedEncodingException e)
 {}
}
return value;
  }
}






POST方式
Http协议介绍
POST  /web/ManageServlet  HTTP/1.1     方式/路径/版本
Accept 可接收的数据类型
Referer  http://192.168.1.100:8080/web/index.jsp   来源路径
Accept-Language 
User-Agent 那个厂商浏览器
Content-Type:用于指定提取数据的内容类型 application/x-www-form-urlencoded
Accept-Encoding:
Host:192.168.1.100;8080
Content-Length:用于指定提取数据的总长度26
Connection:Keep-Alive




title=liming&timelength=90 提取数据


服务端:
public class ManageServlet extends HttpServlet
{
  private static final long serialVersionUID = 1L;
  protected void doGet(HttpServletRequest request,HttpServletResponse response) throws ServletException,IOExceptionprotected void doGet(HttpServletRequest request,HttpServletResponse response) throws ServletException,IOException
  {
    String title = request.getParameter("title");
//title =  new String(title.getBytes("ISO8859-1"),"UTF-8");
String timelength = request.getParameter("timelength");
System.out.println("视频名称:"+title);
System.out.println("时长:"+timelength);
  }
  protected void doPost(HttpServletRequest request,HttpServletResponse response) throws ServletException,IOException
  {
    
  }
}


Android端
public class MainActivity extends Activity
{
  private EditText titleText;
  private EditText lengthText;
  public void onCreate(Bundle savedInstance)
  {
     super.onCreate(Bundle savedInstance);
setContentView(R.layout.main);
titleText =(EditText)this.findViewById(R.id.title);
lengthText =(EditText)this.findViewById(R.id.timelength);
     Button saveButton=(Button) this.findViewById(R.id.button); 
     saveButton.setOnClickListener(new ButtonClickListener());
   }
   private static class ButtonClickListener implements View.OnClickListener
   {
     public void onClick(View v)
{
  String title = titleText.getText().toString();
  String length = lengthText.getText().toString();
  boolean result = NewsService.save(title,length);
  if(result)
  {
    Toast.makeText(getApplicationContext(),R.string.success,1).show();
  }else{
    Toast.makeText(getApplicationContext(),R.string.error,1).show();
  }
}
   }
}


/*保存数据*/
数据通过HTTP协议提交到网络上的web应用get post提交参数,对于2K以下的数据都可以,2K以上的必须使用post。使用get方法需要把参数把附加在路径上




public class NewsService
{
  public static boolean save(String title,String length)
  {
    String path = "http://192.168.1.100:8080/web/ManageServlet";
Map<String,String> params = new HashMap<String,String>();
params.put(("title",title);
params.put("timelength",length);
try
{
return sendPOSTRequest(path,params,"UTF-8");
} catch(Exception e)
{
 e.printStackTrace();
}
return false;
  }
  /*发送POST请求*/
  private static boolean sendPOSTRequest(String path,Map<String , String> params,String ecoding) throws Exception
  {
    //    title=liming&timelength=90
StringBuilder data=http://www.mamicode.com/new StringBuilder();
if(params!=null && !params.isEmpty())
{
 for(Map.Entry<String,String>entry:params.entrySet())    //迭代集合每一个元素
      {
 data.append(entry.getKey()).append("=");
 data.append(URLEncoder.encode(entry.getValue(),ecoding));
 data.append(entry.getKey()).append("&");
 } 
 data.deleteCharAt(data.length() - 1);
}
byte[] entity = data.toString().getBytes();  //默认采用UTF-8得到字节数据
HttpURLConnection conn=(HttpURLConnection) new URL(path).openConnection();
conn.setConnectTimeout(5000);
conn.setRequestMethod("POST");
conn.setDoOutput(true);  //允许对外输出数据
conn.setRequestProperty("Content-Type","application/x-www-form-urlencoded");
conn.setRequestProperty("Content-Length",String.valueOf(entity.length));
OutputStream outStream = conn.getOutputStream();
outStream.write(entity);   //数据并没有写入web应用,只是输出到缓存,只有获得响应码后才输出到web应用
if(conn.getResponseCode() ==200)
{
 return true;
}

return false;
 }
 
Android HttpClient框架
可以完成浏览器完成的功能
public class NewsService
{
  public static boolean save(String title,String length)
  {
    String path = "http://192.168.1.100:8080/web/ManageServlet";
Map<String,String> params = new HashMap<String,String>();
params.put(("title",title);
params.put("timelength",length);
try
{
 return sendHttpClientPOSTRequest(path,params,"UTF-8");
} catch(Exception e)
{
 e.printStackTrace();
}
return false;
  }
  /*发送POST请求*/
  private static boolean sendHttpClientPOSTRequest(String path,Map<String , String> params,String ecoding) throws Exception
  {
    List<NameValuePair> pairs = new ArrayList<NameValuePair>();    //存放请求参数
if(params !=null && !=params.isEmpty())
{
 for(Map.Entry<String,String> entry : params.entrySet())
 {
   pairs.add(new BasicNameValuePair(entry.getKey(),entry.getValue()));

 }
}
  //    title=liming&timelength=90
  UrlEncodingFormEntity entity = new UrlEncodingFormEntity(pairs,encoding);
  HttpPost httpPost=new HttpPost(path);
  httpPost.setEntity(entity);
  DefaultHttpClient client =  new DefaultHttpClient();
  client.execute(httpPost);
  HttpResponse response = client.execute(httpPost);
if( response.getStatusLine().getStatusCode() ==200)
{
  return true;
}
return false;
 }