【Android】使用Gson和Post请求和服务器通信
一、需求文档如下:
URL:http://108.188.129.56:8080/example/cal
请求格式: {"para1":10,"para2":2,"opt":"div"}
请求参数说明:para1表示第一个参数,para2表示第二个参数,opt表示四则运算操作,可取的值为plus、sub、mult、div,分别对应加、减、乘、除
响应格式: {"code":0,"result":5}
响应参数说明:
code为响应码,0表示正常,其他值表示接口调用异常(例如:-1表示参数格式不正确,1表示除数为0等等)
二、Java代码如下
1、切换Android Studio视图,从Android切换到Project,然后将Gson包放到...\app\libs文件夹下。
2、打开app-src-build.gradle,加上依赖语句:compile fileTree(dir: 'libs', include: ['*.jar']),如下:(如已经有则不必添加)
dependencies { compile fileTree(dir: 'libs', include: ['*.jar']) androidTestCompile('com.android.support.test.espresso:espresso-core:2.2.2', { exclude group: 'com.android.support', module: 'support-annotations' }) compile 'com.android.support:appcompat-v7:25.1.0' testCompile 'junit:junit:4.12' }
3、然后代码编辑界面的上方会出现提示:Gradle Files 已经被修改,需要同步。点击右上角的Sync now即可。
4、添加Java代码。
public class MainActivity extends AppCompatActivity { private final int POST_VALUE = 1; String text = ""; //这里不能获取ID,因为下面还没连接到activity_main,xml TextView textView; //--------------------------------------------定义一个Handler来处理消息---------------------------------------------- final Handler handler = new Handler() { @Override public void handleMessage(Message message) { switch (message.what) { case POST_VALUE: textView.setText(text = (text + "=" + message.obj)); text = ""; break; default: break; } } }; //----------------------------------------------------------------------------------------------------- @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); textView = (TextView) findViewById(R.id.textView); //-------------------------------------------设置符号=的监听-------------------------------------------------- Button sendGET = (Button) findViewById(R.id.send); sendGET.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View view) { try { //新建一个线程,通过Message消息通知Handle对UI进行更改,现在只能在UI线程里对UI组件进行更改。 new Thread(new Runnable() { @Override public void run() { if(strTmp.length==2){ //下面三句话,将会把三个参数包装为{"para1":10,"para2":2,"opt":"div"}字段 CalBean tb = new CalBean(10, 2, “plus”); Gson gson = new Gson(); //传入的参数 String datas = gson.toJson(tb); String url = "http://108.188.129.56:8080/example/cal"; String data = sendPostRequest(url, datas); Message message = new Message(); message.what = POST_VALUE; message.obj = data.toString(); handler.sendMessage(message); } } }).start(); } catch (Exception e) { Log.i("ok", "there must be something wrong!"); return; } } }); //----------------------------------------------------------------------------------------------------- } public static String sendPostRequest(String url, String param) { HttpURLConnection httpURLConnection = null; OutputStream out = null; //写 InputStream in = null; //读 int responseCode = 0; //远程主机响应的HTTP状态码 String result = ""; try { URL sendUrl = new URL(url); httpURLConnection = (HttpURLConnection) sendUrl.openConnection(); //post方式请求 httpURLConnection.setRequestMethod("POST"); //设置头部信息 httpURLConnection.setRequestProperty("headerdata", "ceshiyongde"); //一定要设置 Content-Type 要不然服务端接收不到参数 httpURLConnection.setRequestProperty("Content-Type", "application/Json; charset=UTF-8"); //指示应用程序要将数据写入URL连接,其值默认为false(是否传参) httpURLConnection.setDoOutput(true); //httpURLConnection.setDoInput(true); httpURLConnection.setUseCaches(false); httpURLConnection.setConnectTimeout(30000); //30秒连接超时 httpURLConnection.setReadTimeout(30000); //30秒读取超时 //传入参数 out = httpURLConnection.getOutputStream(); out.write(param.getBytes()); out.flush(); //清空缓冲区,发送数据 out.close(); responseCode = httpURLConnection.getResponseCode(); //获取请求的资源 BufferedReader br = new BufferedReader(new InputStreamReader(httpURLConnection.getInputStream(), "UTF-8")); result = br.readLine(); } catch (Exception e) { e.printStackTrace(); } Map<String, String> map = new Gson().fromJson(result, new TypeToken<Map<String, String>>() { }.getType()); return map.get("result"); } }
5、在MainActivity同级目录下新建一个包Bean,在包下新建一个CalBean的Java类,添加如下代码。
public class CalBean { private float para1; private float para2; private String opt; public CalBean(float para1, float para2, String opt) { this.para1 = para1; this.para2 = para2; this.opt = opt; } public CalBean(){}; public float getpara1() { return para1; } public float getPara2() { return para2; } public String getOpt() { return opt; } public void setpara1(float para1) { this.para1 = para1; } public void setPara2(float para2) { this.para2 = para2; } public void setOpt(String opt) { this.opt = opt; } @Override public String toString() { return "CalBean{" + "para1=" + para1 + ", para2=" + para2 + ", opt='" + opt + '\'' + '}'; } }
三、界面布局如下
<?xml version="1.0" encoding="utf-8"?> <GridLayout xmlns:android="http://schemas.android.com/apk/res/android" xmlns:tools="http://schemas.android.com/tools" android:id="@+id/activity_main" android:layout_width="match_parent" android:layout_height="match_parent" android:rowCount="7" android:columnCount="4" tools:context="com.example.weihy.fourfour.MainActivity" > <TextView android:layout_width="match_parent" android:layout_height="100dp" android:id="@+id/textView" android:layout_columnSpan="4" /> <Button android:layout_width="wrap_content" android:layout_height="wrap_content" android:text="=" android:id="@+id/send" /> </GridLayout>
四、打开网络请求
<?xml version="1.0" encoding="utf-8"?> <manifest xmlns:android="http://schemas.android.com/apk/res/android" package="com.example.weihy.fourfour"> <uses-permission android:name="android.permission.INTERNET"/> <application android:allowBackup="true" android:icon="@mipmap/ic_launcher" android:label="@string/app_name" android:supportsRtl="true" android:theme="@style/AppTheme"> <activity android:name=".MainActivity"> <intent-filter> <action android:name="android.intent.action.MAIN" /> <category android:name="android.intent.category.LAUNCHER" /> </intent-filter> </activity> </application> </manifest>
五、分析
观察发现,gson.toJson的作用就是把para1=102.0等号左边的加上转意符\弄成有“”扩着的,在等号右边的有‘’号的话,也加上\弄成双引号“”。
花括号不会有引号扩着,只有最外边的大引号左右扩住全部,CalBean这几个字好像没什么用,修改掉也没什么异常。
【Android】使用Gson和Post请求和服务器通信的更多相关文章
- Android操作HTTP实现与服务器通信(转)
Android操作HTTP实现与服务器通信 本示例以Servlet为例,演示Android与Servlet的通信. 众所周知,Android与服务器通信通常采用HTTP通信方式和Socket通信方 ...
- Android 采用post方式提交数据到服务器
接着上篇<Android 采用get方式提交数据到服务器>,本文来实现采用post方式提交数据到服务器 首先对比一下get方式和post方式: 修改布局: <LinearLayout ...
- 客户端(android,ios)与服务器通信
android,ios客户端与服务器通信为了便于理解,直接用PHP作为服务器端语言 其实就是一个 http请求响应的过程序,先从 B/S模式说起浏览器发起http请求,服务器响应请求,并把数据返回给浏 ...
- Android操作HTTP实现和服务器通信
众所周知,Android与服务器通信通常采用HTTP通信方式和Socket通信方式,而HTTP通信方式又分get和post两种方式.至于Socket通信会在以后的博文中介绍. HTTP协议简介: HT ...
- Android版本28使用http请求
Android版本28使用http请求报错not permitted by network security policy android模拟器调试登录的时候报错 CLEARTEXT communic ...
- Android版本28使用http请求报错not permitted by network security policy
Android版本28使用http请求报错not permitted by network security policy android模拟器调试登录的时候报错 CLEARTEXT communic ...
- HTTP基础与Android之(安卓与服务器通信)——使用HttpClient和HttpURLConnection
查看原文:http://blog.csdn.net/sinat_29912455/article/details/51122286 1客户端连接服务器实现内部的原理 GET方式和POST方式的差别 H ...
- Android+Tomcat通过http获取本机服务器资源
写在前面:本博客为本人原创,严禁任何形式的转载!本博客只允许放在博客园(.cnblogs.com),如果您在其他网站看到这篇博文,请通过下面这个唯一的合法链接转到原文! 本博客全网唯一合法URL:ht ...
- Android操作HTTP实现与服务器通信
(转自http://www.cnblogs.com/hanyonglu/archive/2012/02/19/2357842.html) 本示例以Servlet为例,演示Android与Servlet ...
随机推荐
- Lintcode--003(乱序字符串)
给出一个字符串数组S,找到其中所有的乱序字符串(Anagram).如果一个字符串是乱序字符串,那么他存在一个字母集合相同,但顺序不同的字符串也在S中. 注意事项 所有的字符串都只包含小写字母 样例 ...
- linux中screen命令的用法
http://www.9usb.net/201002/linux-screen-mingling.html 作为linux服务器管理员,经常要使用ssh登陆到远程linux机器上做一些耗时的操作.也许 ...
- ubuntu12.04下同步cm10源码(个人记录,当作笔记)
环境:AMD N850,4G,ubuntu12.04 x64, 老规矩,先是各种依赖: sudo apt-get install git-core gnupg flex bison python ra ...
- 阅读记录:Learning multiple layers of representation(杂乱笔记)
典型的浅层学习结构: 传统隐马尔可夫模型(HMM).条件随机场 (CRFs).最大熵模型(Maxent).支持向量机(SVM).核回归及仅含单隐层的多层感知器(MLP)等. 局部表示,分布式表示和稀疏 ...
- Haskell趣學指南--这个有意思
正在慢慢了解不同于命令式的函数式语言. 希望能获得新的视野.. ~~~~~~~~~~~ http://learnyouahaskell-zh-tw.csie.org/zh-cn/ready-begin ...
- Codeforces 161D Distance in Tree
题目大意:给出一棵n个节点的树,统计树中长度为k的路径的条数(1<=n<=50000 , 1<=k<=500) 思路:树分治! #include<cstdio> # ...
- VMware虚拟机相关文件问题
.vmx VM的配置文件 .vmdk VM的虚拟硬盘 .vmsd VM快照和相关联的vmdk的字典文件 .vswap 虚拟交换文件 .nvram 虚拟机的BIOS信息.VM会生成VMX, VMDK, ...
- jQuery----blur()方法
当元素失去焦点时发生 blur 事件. blur() 函数触发 blur 事件,或者如果设置了 function 参数,该函数也可规定当发生 blur 事件时执行的代码. 提示:早前,blur 事件仅 ...
- 简学LINGO(三)——实例篇
1. 装配线平衡模型 一个装配线含有一系列的工作站.在终于产品的加工过程中每一个工作站运行一种或者是几种特定的任务.装配线周期是指全部工作站完毕分配给他们各自任务所花费时间的最大值.平衡装配线的目标是 ...
- Ubuntu下访问SSH
ssh程序分为有客户端程序openssh-client和服务端程序openssh-server.如果需要ssh登陆到别的电脑,需要安装openssh-client,该程序ubuntu是默认安装的.而如 ...