Android(安卓)GET,POST向服务器端发送数据(发送)
16lz
2021-01-25
//目录结构
//strings.xml字符常量文件
- <?xmlversion="1.0"encoding="utf-8"?>
- <resources>
- <stringname="title">通过Get和Post两种方式分别提交数据到服务器</string>
- <stringname="app_name">GetAndPostRequest</string>
- <stringname="book_name">书本名称</string>
- <stringname="book_price">书本价格</string>
- <stringname="success">提交成功</string>
- <stringname="error">提交失败</string>
- <stringname="get_request">Get请求提交</string>
- <stringname="post_request">Post请求提交</string>
- </resources>
- <?xmlversion="1.0"encoding="utf-8"?>
- <LinearLayoutxmlns:Android="http://schemas.android.com/apk/res/android"
- android:layout_width="fill_parent"
- android:layout_height="fill_parent"
- android:orientation="vertical">
- <TextView
- android:layout_width="fill_parent"
- android:layout_height="wrap_content"
- android:text="@string/title"/>
- <TextView
- android:layout_width="fill_parent"
- android:layout_height="wrap_content"
- android:text="@string/book_name"
- />
- <EditText
- android:id="@+id/book_name"
- android:layout_width="fill_parent"
- android:layout_height="wrap_content"
- />
- <TextView
- android:layout_width="fill_parent"
- android:layout_height="wrap_content"
- android:text="@string/book_price"
- />
- <EditText
- android:id="@+id/book_price"
- android:numeric="integer"
- android:layout_width="fill_parent"
- android:layout_height="wrap_content"
- />
- <LinearLayout
- android:orientation="horizontal"
- android:layout_width="fill_parent"
- android:layout_height="wrap_content"
- >
- <Button
- android:id="@+id/get_reqeust"
- android:layout_width="wrap_content"
- android:layout_height="wrap_content"
- android:text="@string/get_request"
- />
- <Button
- android:id="@+id/post_reqeust"
- android:layout_width="wrap_content"
- android:layout_height="wrap_content"
- android:text="@string/post_request"
- />
- </LinearLayout>
- </LinearLayout>
- packagesn.len.request;
- importjava.io.OutputStream;
- importjava.net.HttpURLConnection;
- importjava.net.URL;
- importjava.net.URLEncoder;
- importjava.util.Map;
- publicclassRequestService
- {
- //get请求,有文件长度大小限制
- publicstaticbooleangetRequest(StringurlPath)throwsException
- {
- URLurl=newURL(urlPath);
- HttpURLConnectioncon=(HttpURLConnection)url.openConnection();
- con.setRequestMethod("GET");
- con.setReadTimeout(5*1000);
- if(con.getResponseCode()==200)
- {
- returntrue;
- }
- returnfalse;
- }
- //post请求,无文件长度大小限制
- publicstaticbooleanpostRequest(StringurlPath,Map<String,String>map)throwsException
- {
- StringBuilderbuilder=newStringBuilder();//拼接字符
- //拿出键值
- if(map!=null&&!map.isEmpty())
- {
- for(Map.Entry<String,String>param:map.entrySet())
- {
- builder.append(param.getKey()).append('=').append(URLEncoder.encode(param.getValue(),"utf-8")).append('&');
- }
- builder.deleteCharAt(builder.length()-1);
- }
- //下面的Content-Length:是这个URL的二进制数据长度
- byteb[]=builder.toString().getBytes();
- URLurl=newURL(urlPath);
- HttpURLConnectioncon=(HttpURLConnection)url.openConnection();
- con.setRequestMethod("POST");
- con.setReadTimeout(5*1000);
- con.setDoOutput(true);//打开向外输出
- con.setRequestProperty("Content-Type","application/x-www-form-urlencoded");//内容类型
- con.setRequestProperty("Content-Length",String.valueOf(b.length));//长度
- OutputStreamoutStream=con.getOutputStream();
- outStream.write(b);//写入数据
- outStream.flush();//刷新内存
- outStream.close();
- //状态码是不成功
- if(con.getResponseCode()==200)
- {
- returntrue;
- }
- returnfalse;
- }
- }
- packagesn.len.getandpostreq;
- importjava.util.HashMap;
- importjava.util.Map;
- importsn.len.request.RequestService;
- importAndroid.app.Activity;
- importandroid.os.Bundle;
- importandroid.util.Log;
- importandroid.view.View;
- importandroid.view.View.OnClickListener;
- importandroid.widget.EditText;
- importandroid.widget.Toast;
- publicclassGetAndPostRequestActivityextendsActivityimplementsOnClickListener
- {
- @Override
- publicvoidonCreate(BundlesavedInstanceState)
- {
- super.onCreate(savedInstanceState);
- setContentView(R.layout.main);
- Viewget_button=findViewById(R.id.get_reqeust);
- Viewpost_button=findViewById(R.id.post_reqeust);
- get_button.setOnClickListener(this);
- post_button.setOnClickListener(this);
- }
- @Override
- publicvoidonClick(Viewv)
- {
- EditTextbook_name=(EditText)findViewById(R.id.book_name);
- EditTextbook_price=(EditText)findViewById(R.id.book_price);
- Stringbookname=book_name.getText().toString();
- Stringbookprice=book_price.getText().toString();
- switch(v.getId())
- {
- caseR.id.get_reqeust://Get请求
- {
- //第一种可以用字符串拼接
- StringurlPath="http://192.168.0.133/web/index.jsp"+"?type=save&book_name="+bookname+"&book_price="+bookprice+"";
- StringrealPath=urlPath.replaceAll("","");//把多余的空格替换掉
- try
- {
- if(RequestService.getRequest(realPath))
- {
- Toast.makeText(this,R.string.success,Toast.LENGTH_LONG).show();
- }
- }
- catch(Exceptione)
- {
- Toast.makeText(this,R.string.error,Toast.LENGTH_LONG).show();
- e.printStackTrace();
- }
- }break;
- caseR.id.post_reqeust://Post请求
- {
- StringurlPath="http://192.168.0.133/web/index.jsp";
- Map<String,String>map=newHashMap<String,String>();//用集合来做,比字符串拼接来得直观
- map.put("type","save");
- map.put("book_name",bookname);
- map.put("book_price",bookprice);
- try
- {
- if(RequestService.postRequest(urlPath,map))
- {
- Toast.makeText(this,R.string.success,Toast.LENGTH_LONG).show();
- }
- }
- catch(Exceptione)
- {
- Toast.makeText(this,R.string.error,Toast.LENGTH_LONG).show();
- Log.e("ERRORS",e.toString());
- e.printStackTrace();
- }
- }break;
- default:break;
- }
- }
- }
- <%@pagecontentType="text/html"pageEncoding="GBK"language="java"%>
- <%
- Stringtype=request.getParameter("type");
- if(type!=null&&!"".equals(type))
- {
- if(type.equals("save"))
- {
- Stringbook_name=request.getParameter("book_name");
- Stringbook_price=request.getParameter("book_price");
- if((book_name!=null&&!"".equals(book_name))&&(book_price!=null&&!"".equals(book_price)))
- {
- System.out.println("书名"+book_name);
- System.out.println("价格"+book_price);
- }
- }
- }
- %>
//Tomcat服务端响应效果,书名和价格都已经打出来了。
更多相关文章
- 一款常用的 Squid 日志分析工具
- GitHub 标星 8K+!一款开源替代 ls 的工具你值得拥有!
- RHEL 6 下 DHCP+TFTP+FTP+PXE+Kickstart 实现无人值守安装
- Linux 环境下实战 Rsync 备份工具及配置 rsync+inotify 实时同步
- Android(安卓)Studio关联源代码
- Android(安卓)常用技术框架的基本使用
- Retrofit +OKHttp简单封装使用
- Android配置文件权限一览表
- 头像图片任意截取