为了账号安全,请及时绑定邮箱和手机立即绑定

如何利用学一个POST请求

标签:
Java Android

我们要写一个简单的提交请求:

https://img1.sycdn.imooc.com/5fc622170001314805200611.jpg

Layout先写好:

<?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:orientation="vertical"
    android:layout_height="match_parent"
    tools:context=".MainActivity">

   <Button
       android:id="@+id/send_request"
       android:layout_width="match_parent"
       android:layout_height="wrap_content"
       android:layout_margin="10dp"
       android:textColor="#000000"
       android:textSize="18dp"
       android:text="发送请求,获取数据"/>
   <TextView
       android:id="@+id/txt"
       android:layout_width="wrap_content"
       android:layout_height="wrap_content"
      android:textSize="18dp"
       android:visibility="gone"
      android:textColor="#000000"
      android:text="变变变"/>
   <EditText
       android:id="@+id/account"
       android:layout_width="match_parent"
       android:layout_height="wrap_content"
      android:hint="请输入账号..."
      android:textColor="#000000"
      android:textSize="18dp"/>

   <EditText
       android:id="@+id/password"
       android:layout_width="match_parent"
       android:layout_height="wrap_content"
      android:hint="请输入密码..."
      android:textSize="18dp"
      android:textColor="#000000"/>
   <Button
       android:id="@+id/btn_upload"
       android:layout_width="wrap_content"
       android:layout_height="wrap_content"
      android:text="提交"
      android:textColor="#000000"
      android:textSize="18dp"/>
</LinearLayout>

接着主代码:

package com.example.httptryapplication;

import androidx.appcompat.app.AppCompatActivity;

import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.TextView;

import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.net.HttpURLConnection;
import java.net.MalformedURLException;
import java.net.URL;

public class MainActivity extends AppCompatActivity {
 private Button send_request;
 private TextView txt;
 private String msg;
 private Button btn_upload;
 private EditText account;
 private EditText password;
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        txt = findViewById(R.id.txt);
        btn_upload =findViewById(R.id.btn_upload);
        send_request = findViewById(R.id.send_request);
        account = findViewById(R.id.account);
        password = findViewById(R.id.password);

        btn_upload.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                final String input_account = account.getText().toString();
                final String input_password = password.getText().toString();
                new Thread(){
                    @Override
                    public void run() {
                        super.run();
                        postInfo(input_account,input_password);
                    }
                }.start();
            }
        });
        send_request.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                new Thread(){
                    @Override
                    public void run() {
                        super.run();
                    msg =  getRequest();
                   runOnUiThread(new Runnable() {
                       @Override
                       public void run() {
                           txt.setText(msg);
                       }
                   });

                    }
                }.start();
            }
        });
    }

    private void postInfo(String account,String password) {
        try {
            URL url = new URL("http://www.imooc.com/api/okhttp/postmethod");
            HttpURLConnection conn = (HttpURLConnection) url.openConnection();
            conn.setRequestMethod("POST");
            conn.setConnectTimeout(6000);
            //设置允许输出,对于客户端,我们提交参数到服务端,我们是在向外输出内容
            conn.setDoOutput(true);
            //待提交的内容如何过去呢?我们就需要把待提交的内容,添加到请求正文
            //设置提交数据的类型,设置和你提交内容相关的属性
            conn.setRequestProperty("Content-Type","application/x-www-form-urlencoded");
            //获取输出流
           OutputStream out =  conn.getOutputStream();
           //写数据
            out.write(("username="+account+"&pwd="+password).getBytes());

            if(conn.getResponseCode() == HttpURLConnection.HTTP_OK){
                InputStream in = conn.getInputStream();
                byte[] b = new byte[1024];
                int len = 0;
              //创建一个缓存流
                ByteArrayOutputStream baos = new ByteArrayOutputStream();
                while ((len = in.read(b))>-1){
                    baos.write(b);

                }
                //取出我们能够看懂的东西
                String msg = new String(baos.toString());
                Log.e("TAG",msg+"======");


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

    private String getRequest() {
        try {
            URL url = new URL("http://www.imooc.com/api/teacher?type=3&cid=1&type=3");
            //获取一个HttpUrlConnection对象
            HttpURLConnection conn = (HttpURLConnection) url.openConnection();
            //请求方式
            conn.setRequestMethod("GET");
            //请求时长
            conn.setConnectTimeout(6000);
            //获取响应码 200:成功 ;404:未请求到指定资源 500:服务器异常
            if(conn.getResponseCode() == HttpURLConnection.HTTP_OK){
                //获取输入流
                InputStream in = conn.getInputStream();
                //字节流的内存设置
                byte[] b = new byte[1024];
                int len = 0;
                //缓存流
                ByteArrayOutputStream baos = new ByteArrayOutputStream();
                //循环读取入输入流
                while((len=in.read(b))>-1){
                    //将字节数组里面的内容存入到缓存流
                    //参数1.待写入的数组 2.起点 3.长度
                    baos.write(b,0,len);
                }
                //接着,我们要把数据转成我们能读懂的内容
                msg = new String(baos.toString());
                Log.e("TAG","msg = "+ msg);

            }

        } catch (MalformedURLException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        }
        return msg;

    }




}

接下来,把用户名和密码解析出来,你是不是以为你能解析一个Post?不行哈!我们的解析例子,是随便举一个GET请求的解析例子:

package com.example.httptryapplication;

import androidx.appcompat.app.AppCompatActivity;

import android.os.Bundle;
import android.widget.EditText;

import org.json.JSONException;
import org.json.JSONObject;

import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.net.HttpURLConnection;
import java.net.MalformedURLException;
import java.net.URL;

public class SecondActivity extends AppCompatActivity {
  private EditText edt_name,edt_password;
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_second);
        edt_name = findViewById(R.id.edt_name);
        edt_password = findViewById(R.id.edt_password);

        new Thread(){
            @Override
            public void run() {
                super.run();
                //直接把数据解析出来
                parseByJsonObject();
            }
        }.start();



    }

    private void parseByJsonObject() {
        new Thread(){
            @Override
            public void run() {
                super.run();
                String str = getRequest();
                try {
                    JSONObject jo = new JSONObject(str);
                   final String message = jo.getString("msg");
                    runOnUiThread(new Runnable() {
                        @Override
                        public void run() {
                            edt_name.setText(message);

                        }
                    });
                } catch (JSONException e) {
                    e.printStackTrace();
                }
            }
        }.start();
    }

    private String getRequest() {
        try {
            URL url = new URL("http://www.imooc.com/api/teacher?type=3&cid=1&type=3");
            HttpURLConnection conn = (HttpURLConnection) url.openConnection();
            conn.setRequestMethod("GET");
            conn.setConnectTimeout(6000);
            if(conn.getResponseCode() == HttpURLConnection.HTTP_OK){
                InputStream in = conn.getInputStream();
                byte[] b = new byte[1024];
                ByteArrayOutputStream baos = new ByteArrayOutputStream();
                int len = 0;
                while ((len = in.read(b))>-1){
                    baos.write(b,0,len);
                }
                String msg = baos.toString();
                return msg;


            }
        } catch (MalformedURLException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        }
        return null;

    }


}

HTTP的最佳写法,把GET请求提成一个类:

package com.example.httptryapplication.utils;

import android.util.Log;

import java.io.BufferedReader;
import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.net.HttpURLConnection;
import java.net.MalformedURLException;
import java.net.URL;

public class HttpUtils {

    public static String sendHttpRequest(String address) {
        HttpURLConnection connection = null;
        try {
            URL url = new URL(address);
            connection = (HttpURLConnection)url.openConnection();
            connection.setRequestMethod("GET");
            connection.setConnectTimeout(8000);
            connection.setReadTimeout(8000);
            connection.setDoOutput(true);
            connection.setDoInput(true);
            InputStream in = connection.getInputStream();
            BufferedReader reader = new BufferedReader(new InputStreamReader(in));
            StringBuilder response = new StringBuilder();
            String line;
            while((line = reader.readLine())!=null){
                response.append(line);
            }
            return response.toString();
        } catch (MalformedURLException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
            return e.getMessage();

        }finally {
            if(connection != null){
                connection.disconnect();
            }
        }
        return null;

    }

}

调用的时候:

String address = "http://baidu.com";

String response = HttpUtils.sendHttpRequest(address);




点击查看更多内容
TA 点赞

若觉得本文不错,就分享一下吧!

评论

作者其他优质文章

正在加载中
  • 推荐
  • 1
  • 收藏
  • 共同学习,写下你的评论
感谢您的支持,我会继续努力的~
扫码打赏,你说多少就多少
赞赏金额会直接到老师账户
支付方式
打开微信扫一扫,即可进行扫码打赏哦
今天注册有机会得

100积分直接送

付费专栏免费学

大额优惠券免费领

立即参与 放弃机会
意见反馈 帮助中心 APP下载
官方微信

举报

0/150
提交
取消