博观而约取,厚积而薄发。这篇文章主要讲述Android使用Gson和Post请求和服务器通信相关的知识,希望能为你提供帮助。
一、需求文档如下:
二、java代码如下
public class MainActivity extends AppCompatActivity { 26private final int POST_VALUE = https://www.songbingjia.com/android/1; 42String text =""; //这里不能获取ID,因为下面还没连接到activity_main,xml TextView textView; //--------------------------------------------定义一个Handler来处理消息---------------------------------------------- final Handler handler = new Handler() { @Override public void handleMessage(Message message) { switch (message.what) { 54case POST_VALUE: textView.setText(text = (text + "=" + message.obj)); text = ""; break; 103default: break; } } }; //----------------------------------------------------------------------------------------------------- @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); textView = (TextView) findViewById(R.id.textView); 131
//-------------------------------------------设置符号=的监听-------------------------------------------------- Button sendGET = (Button) findViewById(R.id.send); sendGET.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View view) {152new Thread(new Runnable() { @Override public void run() { if(strTmp.length==2){ CalBean tb = new CalBean(10, 2, plus); Gson gson = new Gson(); //传入的参数 String datas = gson.toJson(tb); String url = "http://100.108.129.56:8080/example/cal"; String data = https://www.songbingjia.com/android/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"); } }
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>
【Android使用Gson和Post请求和服务器通信】
推荐阅读
- Android注解利器(ButterKnife 的基本使用)
- Android广播机制(转)
- 理解Android的startservice和bindservice(转)
- 常见数据结构的实时应用详细介绍
- InfyTQ面试经验(升级测试)
- 算法设计(反转链表代码实现)
- 算法设计(通配符模式匹配算法原理和实现)
- 计算一个给定字符串的子字符串,该字符串的变位是回文
- 如何在不使用临时变量的情况下交换两个数字()