一、需求文档如下:

  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这几个字好像没什么用,修改掉也没什么异常。

最新文章

  1. 六个漂亮的 ES6 技巧
  2. 【mysql】关于循环插入数据 存储设计
  3. Fire
  4. Debian 8下vsftpd安装与配置
  5. Dolphin for Android(v11.5.1[Jetpack:内置])
  6. 翻译「C++ Rvalue References Explained」C++右值引用详解 Part3:右值引用
  7. HashMap源代码深入剖析
  8. MySQL sql 执行步骤
  9. 转:HTML 5 控件事件属性
  10. 如何使用SetTimer MFC 不够具体
  11. PAT (Advanced Level) 1072. Gas Station (30)
  12. 深入理解MyBatis框架的的配置信息
  13. Swing 混合布局
  14. .NET Core实战项目之CMS 第十六章 用户登录及验证码功能实现
  15. zabbix 自动发现端口并添加监控设置
  16. 如何将AAC音频转换成MP3格式
  17. [python]python官方原版编码规范路径
  18. java.io.BufferedInputStream 源码分析
  19. 【加密算法】MD5
  20. Codeforces Round #295 (Div. 2)B - Two Buttons BFS

热门文章

  1. Method Swizzling以及AOP编程:在运行时进行代码注入-备用
  2. Unity GUI 用C#和Javascript写法的区别
  3. Nexus Root Toolkit教程—— 解锁与Root
  4. cpm效果介绍
  5. 奇葩的SQL*Net more data from client等待,导致批处理巨慢
  6. 关于Set Nocount ON的性能 |c#调用存储过程的返回值总是-1
  7. javascript 典型闭包的用法
  8. HDU---4417Super Mario 树状数组 离线操作
  9. hdu 5012 Dice
  10. Cannot find class in classpath 报错