Android向后台发送请求

1.本篇主要实现用Get和Post提交完成登录案例。2.使用Post提交JSON数据。


代码

使用Get和Post分别实现登录案例

移动端

  • NetUtil
public class NetUtil {


    /**
     * 使用GET访问网络
     *
     * @param username
     * @param password
     * @return 服务器返回的结果
     */
    public static String loginOfGet(String username, String password) {

        HttpURLConnection sConnection = null;

        String data = "username=" + username + "&password=" + password;

        try {
            URL url = new URL("http://XXX:8080/Login?" + data);
            sConnection = (HttpURLConnection) url.openConnection();
            sConnection.setRequestMethod("GET");
            sConnection.setConnectTimeout(10000);
            sConnection.setReadTimeout(10000);
            sConnection.connect();

            int code = sConnection.getResponseCode();
            if (code == 200) {

                InputStream is = sConnection.getInputStream();
                String state = getStringFromInputStream(is);
                return state;
            }
        } catch (MalformedURLException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        } catch (Exception e) {
            e.printStackTrace();
        } finally {

            if (sConnection != null) {
                sConnection.disconnect();
            }

        }


        return null;

    }


    /**
     * 使用POST访问网络
     *
     * @param username
     * @param password
     * @return 服务器返回的结果
     */
    public static String LoginOfPost(String username, String password) {
        HttpURLConnection connection = null;
        try {
            URL url = new URL("http://XXX:8080/Login");
            connection = (HttpURLConnection) url.openConnection();
            connection.setRequestMethod("POST");
            connection.setConnectTimeout(10000);
            connection.setReadTimeout(10000);


            /**
             *
             *  public void setDoOutput(boolean dooutput)
             *          将此 URLConnection 的 doOutput 字段的值设置为指定的值.
             *          URL 连接可用于输入和/或输出。如果打算使用 URL 连接进行输出,
             *          则将 DoOutput 标志设置为 true;如果不打算使用,则设置为 false。默认值为 false。
             *          简单一句话:get请求的话默认就行了,post请求需要setDoOutput(true),这个默认是false的。
             */
            connection.setDoOutput(true);

            String data = "username=" + username + "&password=" + password;
            OutputStream outputStream = connection.getOutputStream();
            outputStream.write(data.getBytes());
            outputStream.flush();
            outputStream.close();

            connection.connect();

            if (200 == connection.getResponseCode()) {
                InputStream is = connection.getInputStream();
                String state = getStringFromInputStream(is);
                return state;
            }

        } catch (MalformedURLException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        } catch (Exception e) {
            e.printStackTrace();
        }


        return null;

    }


    private static String getStringFromInputStream(InputStream is) throws Exception {

        ByteArrayOutputStream baos = new ByteArrayOutputStream();
        byte[] buff = new byte[1024];
        int len = -1;
        while ((len = is.read(buff)) != -1) {
            baos.write(buff, 0, len);
        }
        is.close();
        String html = baos.toString();
        baos.close();

        return html;
    }
}
  • LoginActivity
public class LoginActivity extends AppCompatActivity implements View.OnClickListener {

    private String mUsername;
    private String mPassword;

    private static final String TAG = "LoginActivity";
    private EditText mEt_usrename;
    private EditText mEt_password;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_login);


        Button getBtn = findViewById(R.id.get_btn);
        getBtn.setOnClickListener(this);
        Button postBtn = findViewById(R.id.post_btn);
        postBtn.setOnClickListener(this);
        mEt_usrename = findViewById(R.id.et_username);

        mEt_password = findViewById(R.id.et_password);
    }

    @Override
    public void onClick(View view) {
        switch (view.getId()) {
            case R.id.get_btn:
                mUsername = mEt_usrename.getText().toString().trim();
                mPassword = mEt_password.getText().toString().trim();

                Log.d(TAG, "username = "+mUsername + "password = "+mPassword);
                new Thread(new Runnable() {
                    @Override
                    public void run() {

                        final String state = NetUtil.loginOfGet(mUsername, mPassword);

                        runOnUiThread(new Runnable() {
                            @Override
                            public void run() {
                                Toast.makeText(LoginActivity.this, "state="+state, Toast.LENGTH_SHORT).show();
                            }
                        });

                    }
                }).start();

                break;
            case R.id.post_btn:
                mUsername = mEt_usrename.getText().toString().trim();
                mPassword = mEt_password.getText().toString().trim();
                Log.d(TAG, "username = "+mUsername + "password = "+mPassword);

                new Thread(new Runnable() {
                    @Override
                    public void run() {

                        final String state = NetUtil.LoginOfPost(mUsername, mPassword);

                        runOnUiThread(new Runnable() {
                            @Override
                            public void run() {
                                Toast.makeText(LoginActivity.this, "state="+state, Toast.LENGTH_SHORT).show();
                            }
                        });

                    }
                }).start();


                break;
        }

    }

  • activity_login.xml
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:orientation="vertical"
    tools:context="com.wzg.jsondemo.view.LoginActivity">

    <EditText
        android:gravity="center"
        android:id="@+id/et_username"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:hint="请输入姓名"/>

    <EditText
        android:gravity="center"
        android:id="@+id/et_password"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:hint="请输入密码"
        android:inputType="textPassword"/>

    <Button
        android:id="@+id/get_btn"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:text="Get方式提交"/>
    <Button
        android:text="Post方式提交"
        android:id="@+id/post_btn"
        android:layout_width="match_parent"
        android:layout_height="wrap_content" />
    
</LinearLayout>

服务端

@WebServlet(name = "LoginServlet")
public class LoginServlet extends HttpServlet {
    protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        this.doGet(request, response);
    }

    protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {

        String username = request.getParameter("username");
        String password = request.getParameter("password");
        System.out.println("username = "+username + "password = "+password);
        if(username.equals("admin") && password.equals("123456")){
            response.getWriter().println("success");
        }else{
            response.getWriter().println("failed");
        }
    }
}

向后台发送简单的Json数据

public class MainActivity extends AppCompatActivity implements View.OnClickListener {

    private TextView mJsonTxt;

    private static final String TAG = "MainActivity";

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);


        initViews();

    }

    private void initViews() {

        Button sendJson = findViewById(R.id.send_json);
        sendJson.setOnClickListener(this);

    }

    @Override
    public void onClick(View view) {
        switch (view.getId()) {
            case R.id.send_json:
                new Thread(new Runnable() {
                    @Override
                    public void run() {
                        HttpURLConnection connection = null;
                        // 封装CollegeStudent
                        try {
                            JSONObject jsonObject = new JSONObject();
                            jsonObject.put("num", 1);
                            jsonObject.put("name", "WangXiaoNao");
                            jsonObject.put("age", 20);

                            String s = String.valueOf(jsonObject);

                            Log.d(TAG, "run: ------>" + s);
                            URL url = new URL("http://XXX:8080/ReceiveJson");
                            connection = (HttpURLConnection) url.openConnection();
                            connection.setConnectTimeout(5000);
                            connection.setConnectTimeout(5000);
                            connection.setRequestMethod("POST");
                            connection.setDoOutput(true);
                            connection.setRequestProperty("User-Agent", "Fiddler");
                            connection.setRequestProperty("Content-Type", "application/json");
                            connection.setRequestProperty("Charset", "UTF-8");
                            OutputStream outputStream = connection.getOutputStream();
                            outputStream.write(s.getBytes());
                            outputStream.close();
                            if (200 == connection.getResponseCode()) {
                                BufferedReader bufferedReader = new BufferedReader(new InputStreamReader(connection.getInputStream(), "utf-8"));

                                String line = null;
                                String responseData = "";
                                while ((line = bufferedReader.readLine()) != null) {
                                    responseData += line;

                                }

                                Toast.makeText(MainActivity.this, "后台返回的数据:" + responseData, Toast.LENGTH_SHORT).show();
                                
                            }


                        } catch (JSONException e) {
                            e.printStackTrace();
                        } catch (MalformedURLException e) {
                            e.printStackTrace();
                        } catch (IOException e) {
                            e.printStackTrace();
                        }

                    }

                }).start();


                break;
        }
    }
}
最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
  • 序言:七十年代末,一起剥皮案震惊了整个滨河市,随后出现的几起案子,更是在滨河造成了极大的恐慌,老刑警刘岩,带你破解...
    沈念sama阅读 194,491评论 5 459
  • 序言:滨河连续发生了三起死亡事件,死亡现场离奇诡异,居然都是意外死亡,警方通过查阅死者的电脑和手机,发现死者居然都...
    沈念sama阅读 81,856评论 2 371
  • 文/潘晓璐 我一进店门,熙熙楼的掌柜王于贵愁眉苦脸地迎上来,“玉大人,你说我怎么就摊上这事。” “怎么了?”我有些...
    开封第一讲书人阅读 141,745评论 0 319
  • 文/不坏的土叔 我叫张陵,是天一观的道长。 经常有香客问我,道长,这世上最难降的妖魔是什么? 我笑而不...
    开封第一讲书人阅读 52,196评论 1 263
  • 正文 为了忘掉前任,我火速办了婚礼,结果婚礼上,老公的妹妹穿的比我还像新娘。我一直安慰自己,他们只是感情好,可当我...
    茶点故事阅读 61,073评论 4 355
  • 文/花漫 我一把揭开白布。 她就那样静静地躺着,像睡着了一般。 火红的嫁衣衬着肌肤如雪。 梳的纹丝不乱的头发上,一...
    开封第一讲书人阅读 46,112评论 1 272
  • 那天,我揣着相机与录音,去河边找鬼。 笑死,一个胖子当着我的面吹牛,可吹牛的内容都是我干的。 我是一名探鬼主播,决...
    沈念sama阅读 36,531评论 3 381
  • 文/苍兰香墨 我猛地睁开眼,长吁一口气:“原来是场噩梦啊……” “哼!你这毒妇竟也来了?” 一声冷哼从身侧响起,我...
    开封第一讲书人阅读 35,215评论 0 253
  • 序言:老挝万荣一对情侣失踪,失踪者是张志新(化名)和其女友刘颖,没想到半个月后,有当地人在树林里发现了一具尸体,经...
    沈念sama阅读 39,485评论 1 290
  • 正文 独居荒郊野岭守林人离奇死亡,尸身上长有42处带血的脓包…… 初始之章·张勋 以下内容为张勋视角 年9月15日...
    茶点故事阅读 34,578评论 2 309
  • 正文 我和宋清朗相恋三年,在试婚纱的时候发现自己被绿了。 大学时的朋友给我发了我未婚夫和他白月光在一起吃饭的照片。...
    茶点故事阅读 36,356评论 1 326
  • 序言:一个原本活蹦乱跳的男人离奇死亡,死状恐怖,灵堂内的尸体忽然破棺而出,到底是诈尸还是另有隐情,我是刑警宁泽,带...
    沈念sama阅读 32,215评论 3 312
  • 正文 年R本政府宣布,位于F岛的核电站,受9级特大地震影响,放射性物质发生泄漏。R本人自食恶果不足惜,却给世界环境...
    茶点故事阅读 37,583评论 3 299
  • 文/蒙蒙 一、第九天 我趴在偏房一处隐蔽的房顶上张望。 院中可真热闹,春花似锦、人声如沸。这庄子的主人今日做“春日...
    开封第一讲书人阅读 28,898评论 0 17
  • 文/苍兰香墨 我抬头看了看天上的太阳。三九已至,却和暖如春,着一层夹袄步出监牢的瞬间,已是汗流浃背。 一阵脚步声响...
    开封第一讲书人阅读 30,174评论 1 250
  • 我被黑心中介骗来泰国打工, 没想到刚下飞机就差点儿被人妖公主榨干…… 1. 我叫王不留,地道东北人。 一个月前我还...
    沈念sama阅读 41,497评论 2 341
  • 正文 我出身青楼,却偏偏与公主长得像,于是被迫代替她去往敌国和亲。 传闻我的和亲对象是个残疾皇子,可洞房花烛夜当晚...
    茶点故事阅读 40,697评论 2 335

推荐阅读更多精彩内容

  • Spring Cloud为开发人员提供了快速构建分布式系统中一些常见模式的工具(例如配置管理,服务发现,断路器,智...
    卡卡罗2017阅读 134,497评论 18 139
  • 随笔中默认的包为com.demo默认接口:Demo实现类:Demo1,Demo2 使用spring注解第一步,需要...
    易燃易爆炸_62a8阅读 181评论 0 1
  • 先说下,这次亲子游,由于临时有事情,走不出的爸爸不止一位,50人中,只有两个爸爸啦…所以我们这些妈妈们有力出力,累...
    宁的水煮鱼阅读 700评论 0 1
  • 时光会慢慢的流 我也会离你越来越近 很多时候我不曾想起你 我早已不记得你的容颜 我早已不记得你的微笑 我早已不记得...
    雨藕阅读 126评论 0 0
  • 当你面对一件新生事物,你从来没有学过新知识或从未接触过的新技能的时候,你是怎样学习和练习的。是走一步瞧一步的见子打...
    linhuizhang阅读 586评论 0 0