Http 的Get 和Post 请求

在发送http请求之前先在AndroidManifest.xml文件中添加网络权限:

<uses-permission android:name="android.permission.INTERNET"/>

切记:网络请求需要启动一个新的线程:


Http 发送get请求:

/**http的Get请求
     *
     * @param view
     */
    public void httpGet(View view) {

        new Thread(){

            @Override
            public void run() {
                super.run();
                String result = "";//结果
                String str = "";//每一行
                try {

                    URL  url = new URL("http://192.168.4.15:8080/LoginTest/servlet/Login?userName=123&psw=123");
                    HttpURLConnection connection  = (HttpURLConnection) url.openConnection();
                    InputStream inputStream = connection.getInputStream();
                    BufferedReader bufferedReader = new BufferedReader(new InputStreamReader(inputStream));
                    while (!TextUtils.isEmpty(str = bufferedReader.readLine())){
                        result += str;
                    }
                    Log.d("lisc", "httpGet: "+result);
                } catch (Exception e) {
                    e.printStackTrace();
                }
            }
        }.start();

    }

Http 发送 post请求:

/**
     * http的post请求
     * @param view
     */
    public void httpPost(View view) {

        new Thread(){
            @Override
            public void run() {
                super.run();
                String result = "";
                String str = "";
                try {
                    URL  url = new URL("http://192.168.4.15:8080/LoginTest/servlet/Login");
               HttpURLConnection connection = (HttpURLConnection) url.openConnection();
               connection.setDoOutput(true);//允许在请求体写入内容
                OutputStream outputStream =  connection.getOutputStream();
                outputStream.write("userName=13&psw=123".getBytes());

                InputStream inputStream =  connection.getInputStream();
                BufferedReader reader = new BufferedReader(new InputStreamReader(inputStream));

                  while (!TextUtils.isEmpty(str = reader.readLine())){

                      result += str;
                  }
                    Log.d("lsc", "run: "+result);

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

            }
        }.start();

    }



猜你喜欢

转载自blog.csdn.net/weixin_42190712/article/details/80313307