Android向服务器传递参数方式:Post&Get

因为平时开发原因,遇到了问题,都是上网去查询解决方法,但是没有记录的习惯,下次碰见了这个问题又要去网上搜索解决方法,这样既没有效率,又对自己的能力没有多大提升,因此才萌生了写博客的想法。既是将平时遇到的问题记录下来,又可以和博友们一起分享(ps:经常看别人的博客,自己没有一点贡献,实在说不过去啊,这和微信群抢红包,只抢不发是一个道理的咯,哈哈!!!),还能对自己的能力有所锻炼。好了,这篇博客就写一下关于Android客户端向服务器发送网络请求时,传递参数的方式。

在Android中网络编程中,既提供了标准Java接口HttpURLConnection和Apache接口HttpClient(Android 4.0之后被废弃了),也涌现了大量的网络请求开源框架,比如Volley、okHttp、Retrofit等,这篇文章由于篇幅和时间关系,就先谈谈Android自身提供的HttpURLConnection接口怎么向服务器传递参数,有时间可以和大家谈谈Volley和Retrofit这些开源网络框架的使用(PS:至于这些开源框架的原理,呃呃,其实我也不懂,哈哈大笑)。

学过网络编程的同学应该都知道通过HTTP协议,向服务器传递数据,无非就Get和Post这两种方法。

Get方法是将参数附加到Url后进行传输,比如url="http:127.0.0.1:8080/Test/LoginServlet?username=张三&password=123456",它的优点就是直观,缺点就是数据量小、不安全。

  1. StringBuffer sb = new StringBuffer();  
  2.    URL url = new URL("http://127.0.0.1:8080/Test/LoginServlet?username=张三&password=123456");  
  3.   
  4.    //获取连接对象,此时未建立连接  
  5.    HttpURLConnection conn = (HttpURLConnection) url.openConnection();  
  6.   
  7.    //设置请求方式为Get请求  
  8.    conn.setRequestMethod("GET");  
  9.   
  10.    //设置连接超时  
  11.    conn.setConnectTimeout(5000);  
  12.   
  13.    //设置读取超时  
  14.    conn.setReadTimeout(5000);  
  15.    int code = conn.getResponseCode();  
  16.    //获得响应状态  
  17.    int resultCode = httpConn.getResponseCode();  
  18.    if (HttpURLConnection.HTTP_OK == resultCode) {  
  19.        String readLine = "";  
  20.        BufferedReader responseReader = new BufferedReader(new InputStreamReader(httpConn.getInputStream(), "UTF-8"));  
  21.        while ((readLine = responseReader.readLine()) != null) {  
  22.            sb.append(readLine).append("\n");  
  23.        }  
  24.        responseReader.close();  
  25.    }  
  26.    return (sb.toString());  
 StringBuffer sb = new StringBuffer();
    URL url = new URL("http://127.0.0.1:8080/Test/LoginServlet?username=张三&password=123456");

    //获取连接对象,此时未建立连接
    HttpURLConnection conn = (HttpURLConnection) url.openConnection();

    //设置请求方式为Get请求
    conn.setRequestMethod("GET");

    //设置连接超时
    conn.setConnectTimeout(5000);

    //设置读取超时
    conn.setReadTimeout(5000);
    int code = conn.getResponseCode();
    //获得响应状态
    int resultCode = httpConn.getResponseCode();
    if (HttpURLConnection.HTTP_OK == resultCode) {
        String readLine = "";
        BufferedReader responseReader = new BufferedReader(new InputStreamReader(httpConn.getInputStream(), "UTF-8"));
        while ((readLine = responseReader.readLine()) != null) {
            sb.append(readLine).append("\n");
        }
        responseReader.close();
    }
    return (sb.toString());

有时候为了图方便,我在开发时会使用Get方法向服务器传参数,但是会碰到服务器报如下错误:

  1. Error parsing HTTP request header  
  2.  Note: further occurrences of HTTP header parsing errors will be logged at DEBUG level.  
Error parsing HTTP request header
 Note: further occurrences of HTTP header parsing errors will be logged at DEBUG level.
因为我对后端不是很熟,就会写一点简单的Servlet、JSP啊,其他就不怎么熟了,网上查了一下,是因为Tomcat的header缓冲区大小不够,只需要在server.xml中增加maxHttpHeaderSize字段即可:

  1. <Connector URIEncoding="UTF-8" port="8080" protocol="org.apache.coyote.http11.Http11NioProtocol"  
  2.     useBodyEncodingForURI="false"  
  3.     enableLookups="false"  
  4.                connectionTimeout="20000"  
  5.                redirectPort="8443" maxHttpHeaderSize="你想要的大小"/>  
<Connector URIEncoding="UTF-8" port="8080" protocol="org.apache.coyote.http11.Http11NioProtocol"
	useBodyEncodingForURI="false"
	enableLookups="false"
               connectionTimeout="20000"
               redirectPort="8443" maxHttpHeaderSize="你想要的大小"/>
我不知道这样有没有用,博友们如果碰到这个问题可以试一下,但是使用Post方法传同样的参数就不会有这个问题,我想应该是Get传递参数的数据量太大,导致的吧。


Post方法是将参数附加在表单中上传给服务器,它的优点是安全、数据量大。

  1. StringBuffer sb = new StringBuffer();  
  2.   //建立连接  
  3.   URL url = new URL("http:127.0.0.1:8080/Test/LoginServlet");  
  4.   HttpURLConnection httpURLConnection = (HttpURLConnection)url.openConnection();  
  5.   httpURLConnection.setConnectTimeout(3000);          //设置连接超时时间  
  6.           httpURLConnection.setDoInput(true);                  //打开输入流,以便从服务器获取数据  
  7.   httpURLConnection.setDoOutput(true);                 //打开输出流,以便向服务器提交数据  
  8.   httpURLConnection.setRequestMethod("POST");        //设置以Post方式提交数据  
  9.           httpURLConnection.setUseCaches(false);               //使用Post方式不能使用缓存  
  10.   //设置请求体的类型是文本类型  
  11.   httpURLConnection.setRequestProperty("Content-Type""application/x-www-form-urlencoded");  
  12.   //传递参数  
  13.   Map<String, String> params = new HashMap<String, String>();  
  14.   params.put("username", username);  
  15.   params.put("password", password);  
  16.   byte[] data = getRequestData(params, encode).toString().getBytes();    //获得请求体  
  17.   //设置请求体的长度  
  18.   httpURLConnection.setRequestProperty("Content-Length", String.valueOf(data.length));  
  19.   //获得输出流,向服务器写入数据  
  20.   OutputStream outputStream = httpURLConnection.getOutputStream();  
  21.   outputStream.write(data);  
  22.   //获得响应状态  
  23.   int resultCode = httpConn.getResponseCode();  
  24.   if (HttpURLConnection.HTTP_OK == resultCode) {  
  25.       String readLine = "";  
  26.       BufferedReader responseReader = new BufferedReader(new InputStreamReader(httpConn.getInputStream(), "UTF-8"));  
  27.       while ((readLine = responseReader.readLine()) != null) {  
  28.           sb.append(readLine).append("\n");  
  29.       }  
  30.       responseReader.close();  
  31.   }  
  32.   return (sb.toString());  
  StringBuffer sb = new StringBuffer();
    //建立连接
    URL url = new URL("http:127.0.0.1:8080/Test/LoginServlet");
    HttpURLConnection httpURLConnection = (HttpURLConnection)url.openConnection();
    httpURLConnection.setConnectTimeout(3000);          //设置连接超时时间
            httpURLConnection.setDoInput(true);                  //打开输入流,以便从服务器获取数据
    httpURLConnection.setDoOutput(true);                 //打开输出流,以便向服务器提交数据
    httpURLConnection.setRequestMethod("POST");        //设置以Post方式提交数据
            httpURLConnection.setUseCaches(false);               //使用Post方式不能使用缓存
    //设置请求体的类型是文本类型
    httpURLConnection.setRequestProperty("Content-Type", "application/x-www-form-urlencoded");
    //传递参数
    Map<String, String> params = new HashMap<String, String>();
    params.put("username", username);
    params.put("password", password);
    byte[] data = getRequestData(params, encode).toString().getBytes();    //获得请求体
    //设置请求体的长度
    httpURLConnection.setRequestProperty("Content-Length", String.valueOf(data.length));
    //获得输出流,向服务器写入数据
    OutputStream outputStream = httpURLConnection.getOutputStream();
    outputStream.write(data);
    //获得响应状态
    int resultCode = httpConn.getResponseCode();
    if (HttpURLConnection.HTTP_OK == resultCode) {
        String readLine = "";
        BufferedReader responseReader = new BufferedReader(new InputStreamReader(httpConn.getInputStream(), "UTF-8"));
        while ((readLine = responseReader.readLine()) != null) {
            sb.append(readLine).append("\n");
        }
        responseReader.close();
    }
    return (sb.toString());

至此,我的第一篇技术博客就完成了,以前经常看别人的博客,现在自己开始写博客,才发现写一篇博客有多么不易啊。


  1.   
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值