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;
        }
    }
}
最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

推荐阅读更多精彩内容

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