码迷,mamicode.com
首页 > 移动开发 > 详细

【Android】使用Gson和Post请求和服务器通信

时间:2017-01-09 23:00:30      阅读:585      评论:0      收藏:0      [点我收藏+]

标签:find   cep   data   rmi   net   class   apk   port   backup   

一、需求文档如下:

 

二、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请求和服务器通信

标签:find   cep   data   rmi   net   class   apk   port   backup   

原文地址:http://www.cnblogs.com/Hystudio-lzu/p/6266675.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!