Android GET,POST向服务器端发送数据(发送)

//目录结构


//strings.xml字符常量文件

  1. <?xml version="1.0" encoding="utf-8"?>  
  2. <resources>  
  3.   
  4.     <string name="title">通过Get和Post两种方式分别提交数据到服务器</string>  
  5.     <string name="app_name">GetAndPostRequest</string>  
  6.     <string name="book_name">书本名称</string>  
  7.     <string name="book_price">书本价格</string>  
  8.     <string name="success">提交成功</string>  
  9.     <string name="error">提交失败</string>  
  10.     <string name="get_request">Get请求提交</string>  
  11.     <string name="post_request">Post请求提交</string>  
  12. </resources>  
//main.xml 布局文件
  1. <?xml version="1.0" encoding="utf-8"?>  
  2. <LinearLayout xmlns:Android="http://schemas.android.com/apk/res/android"  
  3.     android:layout_width="fill_parent"  
  4.     android:layout_height="fill_parent"  
  5.     android:orientation="vertical" >  
  6.   
  7.     <TextView  
  8.         android:layout_width="fill_parent"  
  9.         android:layout_height="wrap_content"  
  10.         android:text="@string/title" />  
  11.     <TextView   
  12.         android:layout_width="fill_parent"  
  13.         android:layout_height="wrap_content"  
  14.         android:text="@string/book_name"  
  15.         />  
  16.     <EditText   
  17.         android:id="@+id/book_name"  
  18.         android:layout_width="fill_parent"  
  19.         android:layout_height="wrap_content"  
  20.         />  
  21.     <TextView   
  22.         android:layout_width="fill_parent"  
  23.         android:layout_height="wrap_content"  
  24.         android:text="@string/book_price"  
  25.         />  
  26.     <EditText   
  27.         android:id="@+id/book_price"  
  28.         android:numeric="integer"  
  29.         android:layout_width="fill_parent"  
  30.         android:layout_height="wrap_content"  
  31.         />  
  32.     <LinearLayout   
  33.         android:orientation="horizontal"  
  34.         android:layout_width="fill_parent"  
  35.         android:layout_height="wrap_content"  
  36.         >  
  37.         <Button   
  38.             android:id="@+id/get_reqeust"  
  39.             android:layout_width="wrap_content"  
  40.             android:layout_height="wrap_content"  
  41.             android:text="@string/get_request"  
  42.             />  
  43.         <Button   
  44.             android:id="@+id/post_reqeust"  
  45.             android:layout_width="wrap_content"  
  46.             android:layout_height="wrap_content"  
  47.             android:text="@string/post_request"  
  48.             />  
  49.     </LinearLayout>  
  50.   
  51. </LinearLayout>  
//RequestService.java 通过GET 和 Post请求的类
  1. package sn.len.request;  
  2.   
  3. import java.io.OutputStream;  
  4. import java.net.HttpURLConnection;  
  5. import java.net.URL;  
  6. import java.net.URLEncoder;  
  7. import java.util.Map;  
  8.   
  9. public class RequestService   
  10. {  
  11.     //get请求,有文件长度大小限制   
  12.     public static boolean getRequest(String urlPath) throws Exception  
  13.     {  
  14.         URL url=new URL(urlPath);  
  15.         HttpURLConnection con=(HttpURLConnection)url.openConnection();  
  16.         con.setRequestMethod("GET");  
  17.         con.setReadTimeout(5*1000);  
  18.         if(con.getResponseCode()==200)  
  19.         {  
  20.             return true;  
  21.         }  
  22.         return false;  
  23.     }  
  24.     //post请求,无文件长度大小限制   
  25.     public static boolean postRequest(String urlPath,Map<String,String> map) throws Exception  
  26.     {  
  27.         StringBuilder builder=new StringBuilder(); //拼接字符   
  28.         //拿出键值   
  29.         if(map!=null && !map.isEmpty())  
  30.         {  
  31.             for(Map.Entry<String, String> param:map.entrySet())  
  32.             {  
  33.                 builder.append(param.getKey()).append('=').append(URLEncoder.encode(param.getValue(), "utf-8")).append('&');  
  34.             }  
  35.             builder.deleteCharAt(builder.length()-1);  
  36.         }  
  37.         //下面的Content-Length: 是这个URL的二进制数据长度   
  38.         byte b[]=builder.toString().getBytes();  
  39.         URL url=new URL(urlPath);  
  40.         HttpURLConnection con=(HttpURLConnection)url.openConnection();  
  41.         con.setRequestMethod("POST");  
  42.         con.setReadTimeout(5*1000);  
  43.         con.setDoOutput(true);//打开向外输出   
  44.         con.setRequestProperty("Content-Type""application/x-www-form-urlencoded");//内容类型   
  45.         con.setRequestProperty("Content-Length",String.valueOf(b.length));//长度   
  46.         OutputStream outStream=con.getOutputStream();  
  47.         outStream.write(b);//写入数据   
  48.         outStream.flush();//刷新内存   
  49.         outStream.close();  
  50.         //状态码是不成功   
  51.         if(con.getResponseCode()==200)  
  52.         {  
  53.             return true;  
  54.         }  
  55.         return false;   
  56.           
  57.     }  
  58. }  
//GetAndPostRequestActivity.java 主要的控制类
  1. package sn.len.getandpostreq;  
  2.   
  3. import java.util.HashMap;  
  4. import java.util.Map;  
  5.   
  6. import sn.len.request.RequestService;  
  7. import Android.app.Activity;  
  8. import android.os.Bundle;  
  9. import android.util.Log;  
  10. import android.view.View;  
  11. import android.view.View.OnClickListener;  
  12. import android.widget.EditText;  
  13. import android.widget.Toast;  
  14.   
  15. public class GetAndPostRequestActivity extends Activity implements OnClickListener  
  16. {  
  17.     @Override  
  18.     public void onCreate(Bundle savedInstanceState)   
  19.     {  
  20.         super.onCreate(savedInstanceState);  
  21.         setContentView(R.layout.main);  
  22.         View get_button=findViewById(R.id.get_reqeust);  
  23.         View post_button=findViewById(R.id.post_reqeust);  
  24.         get_button.setOnClickListener(this);  
  25.         post_button.setOnClickListener(this);  
  26.     }  
  27.   
  28.     @Override  
  29.     public void onClick(View v)   
  30.     {  
  31.         EditText book_name=(EditText)findViewById(R.id.book_name);  
  32.         EditText book_price=(EditText)findViewById(R.id.book_price);  
  33.         String bookname=book_name.getText().toString();  
  34.         String bookprice=book_price.getText().toString();  
  35.         switch(v.getId())  
  36.         {  
  37.             case R.id.get_reqeust: //Get请求   
  38.             {  
  39.                 //第一种可以用字符串拼接   
  40.                 String urlPath="http://192.168.0.133/web/index.jsp"+"?type=save&book_name="+bookname+"&book_price="+bookprice+"";  
  41.                 String realPath=urlPath.replaceAll(" """);//把多余的空格替换掉   
  42.                 try   
  43.                 {  
  44.                     if(RequestService.getRequest(realPath))  
  45.                     {  
  46.                         Toast.makeText(this, R.string.success, Toast.LENGTH_LONG).show();  
  47.                     }  
  48.                 }  
  49.                 catch (Exception e)   
  50.                 {  
  51.                     Toast.makeText(this, R.string.error, Toast.LENGTH_LONG).show();  
  52.                     e.printStackTrace();  
  53.                 }  
  54.             }break;  
  55.             case R.id.post_reqeust: //Post请求   
  56.             {  
  57.                 String urlPath="http://192.168.0.133/web/index.jsp";  
  58.                 Map<String,String> map=new HashMap<String,String>();//用集合来做,比字符串拼接来得直观   
  59.                 map.put("type""save");  
  60.                 map.put("book_name",bookname);  
  61.                 map.put("book_price",bookprice);  
  62.                 try   
  63.                 {  
  64.                     if(RequestService.postRequest(urlPath, map))  
  65.                     {  
  66.                         Toast.makeText(this, R.string.success, Toast.LENGTH_LONG).show();  
  67.                     }  
  68.                 }   
  69.                 catch (Exception e)   
  70.                 {  
  71.                     Toast.makeText(this, R.string.error, Toast.LENGTH_LONG).show();  
  72.                     Log.e("ERRORS", e.toString());  
  73.                     e.printStackTrace();  
  74.                 }  
  75.             }break;  
  76.             default:break;  
  77.         }  
  78.     }  
  79.       
  80. }  
//服务器端代码用JSP实现,就没有写Servlet了
  1. <%@page contentType="text/html" pageEncoding="GBK" language="java"%>  
  2. <%  
  3.     String type=request.getParameter("type");  
  4.     if(type!=null && !"".equals(type))  
  5.     {  
  6.         if(type.equals("save"))  
  7.         {  
  8.             String book_name=request.getParameter("book_name");  
  9.             String book_price=request.getParameter("book_price");  
  10.             if((book_name!=null && !"".equals(book_name)) && (book_price!=null && !"".equals(book_price)))  
  11.             {  
  12.                 System.out.println("书名"+book_name);  
  13.                 System.out.println("价格"+book_price);  
  14.             }  
  15.         }  
  16.     }  
  17. %>  
//效果


//Tomcat服务端响应效果,书名和价格都已经打出来了。


  • 0
    点赞
  • 4
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值