Android 获取外网IP地址 (Wifi 4G 通用)

import android.os.Bundle;
import android.os.Looper;
import com.alibaba.fastjson.JSON;
import java.io.BufferedInputStream;
import java.io.InputStream;
import java.net.HttpURLConnection;
import java.net.URL;
import java.util.Scanner;

public class GetIPActivity extends AppCompatActivity {


    private String ip;
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_get_ip);


        new Thread(new Runnable() {
            @Override
            public void run() {
                Looper.prepare();
                getIp();
                Looper.loop();
            }
        }).start();
        
    }


    private String getIp() {
        HttpURLConnection urlConnection = null;
        try {
            URL url = new URL("http://ip.chinaz.com/getip.aspx");
            urlConnection = (HttpURLConnection)url.openConnection();
            InputStream in = new BufferedInputStream(urlConnection.getInputStream());
            Scanner scanner = new Scanner(in).useDelimiter("\\A");
            String result = scanner.hasNext() ? scanner.next() : "";
            if (!result.isEmpty()){
                Toast.makeText(this,result,Toast.LENGTH_SHORT).show();
                ip = JSON.parseObject(result).getString("ip");
            }
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            urlConnection.disconnect();
            return ip;
        }
    }
    
}

你可能感兴趣的:(Android 获取外网IP地址 (Wifi 4G 通用))