Android使用Gson和Post请求和服务器通信
Posted
tags:
篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了Android使用Gson和Post请求和服务器通信相关的知识,希望对你有一定的参考价值。
一、需求文档如下:
二、Java代码如下
public class MainActivity extends AppCompatActivity { 26 private final int POST_VALUE = 1; 42 String text = ""; //这里不能获取ID,因为下面还没连接到activity_main,xml TextView textView; //--------------------------------------------定义一个Handler来处理消息---------------------------------------------- final Handler handler = new Handler() { @Override public void handleMessage(Message message) { switch (message.what) { 54 case POST_VALUE: textView.setText(text = (text + "=" + message.obj)); text = ""; break;103 default: 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) {152 new 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 = 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请求和服务器通信的主要内容,如果未能解决你的问题,请参考以下文章