1. 程式人生 > >HTTP網路請求POST請求

HTTP網路請求POST請求

1.mainActivity主頁面

package com.example.day01_http_post02;

import android.annotation.SuppressLint;
import android.os.Handler;
import android.os.Message;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.TextView;
import android.widget.Toast;

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

public class MainActivity extends AppCompatActivity {

    private EditText editText;
    private Button button;
    private TextView textView;
    private String result;
    private final int UPDATE_UI = 1;
    @SuppressLint("HandlerLeak")
    private Handler handler = new Handler(){
        @Override
        public void handleMessage(Message msg) {
            switch (msg.what){
                case UPDATE_UI:
                    textView.setText(msg.obj.toString());
                    break;
            }
        }
    };
    private int timeout;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        //獲取資源id
        editText = findViewById(R.id.ed_name);
        button = findViewById(R.id.btn);
        textView = findViewById(R.id.text);
        //點選
        button.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                //判斷網路是否可用
                if(!NetUtil.hasNetWork(MainActivity.this)){
                    Toast.makeText(MainActivity.this,"網路不可用",Toast.LENGTH_SHORT).show();
                    return;
                }
                new Thread(new Runnable() {
                    @Override
                    public void run() {
                        requestData(editText.getText().toString());
                    }


                }).start();
            }
        });
    }
    private String urlStr = "http://tcc.taobao.com/cc/json/mobile_tel_segment.htm";
    private void requestData(String num) {
        try {
            //定義url地址
            URL url = new URL(urlStr);
            //開啟連線
            HttpURLConnection urlConnection = (HttpURLConnection) url.openConnection();
            //設定請求方式
            urlConnection.setRequestMethod("POST");
            //設定超時
            boolean phoneWork = NetUtil.isPhoneWork(MainActivity.this);
            if(phoneWork){
                timeout = 10000;
            }else{
                timeout = 5000;
            }
            urlConnection.setReadTimeout(timeout);
            urlConnection.setConnectTimeout(timeout);
            //表示需要輸出的引數
            urlConnection.setDoOutput(true);
            //輸出引數
            String pames = "tel="+num;
            urlConnection.getOutputStream().write(pames.getBytes());
            urlConnection.getOutputStream().flush();
            //獲取狀態碼
            int responseCode = urlConnection.getResponseCode();
            if(responseCode == 200){
                result = stream2String(urlConnection.getInputStream());
            }else{
                result = "error"+responseCode;
            }
            handler.sendMessage(handler.obtainMessage(UPDATE_UI,result));
        } catch (Exception e) {
            e.printStackTrace();
        }
    }
    //將字元流轉換為字元流
    private String stream2String(InputStream inputStream) throws IOException {
        InputStreamReader isr = new InputStreamReader(inputStream,"gbk");
        BufferedReader br = new BufferedReader(isr);
        StringBuilder builder = new StringBuilder();
        for(String tem = br.readLine();tem!=null;tem = br.readLine()){
            builder.append(tem);
        }
        return builder.toString();
    }
}

2.判斷網路型別和是否有網路

在這裡插入程式碼片package com.example.day01_http_post02;

import android.content.Context;
import android.net.ConnectivityManager;
import android.net.NetworkInfo;

public class NetUtil {
    //判斷網路是否可用
    public static boolean hasNetWork(Context context){
        ConnectivityManager cm = (ConnectivityManager) context.getSystemService(Context.CONNECTIVITY_SERVICE);
        NetworkInfo activeNetworkInfo = cm.getActiveNetworkInfo();
        return activeNetworkInfo!=null && activeNetworkInfo.isAvailable();
    }
    //判斷網路型別
    public static boolean isPhoneWork(Context context){
        ConnectivityManager cm = (ConnectivityManager) context.getSystemService(Context.CONNECTIVITY_SERVICE);
        NetworkInfo activeNetworkInfo = cm.getActiveNetworkInfo();
        return activeNetworkInfo.getType() == ConnectivityManager.TYPE_MOBILE;
    }
}