android真机访问本地局域网tomcat服务器

本文主要探讨如何让Android设备通过WIFI连接局域网内的Tomcat服务器。首先介绍了两种链接方式,包括公网部署和局域网内访问。接着,详细讲述了Android端的开发,特别是页面按钮事件处理和图片下载服务类的实现,同时提到了布局文件的修改以及添加网络访问权限的重要性。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

链接方式:
1)将应用后台服务器部署到某台可以通过公网访问的服务器上,手机访问该公网IP地址,类似于公网试用

(2)设置局域网,手机通过WIFI访问局域网中的某台服务器(拥有局域网IP地址)选择这种方案

下面主要讲android这边的开发

  1. 页面部分的按钮触发事件处理逻辑
/**
     * 按钮触发下载
     * 
     * @param view
     * @throws MalformedURLException
     */
    public void startDownImage(View view) throws MalformedURLException {
        String path = urlEditText.getText().toString();// 获取图片路径字符串
        Toast.makeText(getApplicationContext(), "开始下载图片", Toast.LENGTH_LONG)
                .show();
        Toast.makeText(
                getApplicationContext(),
                "IP: " + this.getLocalIpAddress() + "    MAC: "
                        + this.getLocalMacAddress(), Toast.LENGTH_LONG).show();
        Log.i(TAG, "IP: " + this.getLocalIpAddress());
        Log.i(TAG, "MAC: " + this.getLocalMacAddress());
        // 下载图片,新建一个异步任务下载图片
        ImageService.getImage(showImage, path);

    }

    /**
     * 获取Android本机IP地址
     * 
     * @return
     */
    private String getLocalIpAddress() {
        try {
            for (Enumeration<NetworkInterface> en = NetworkInterface
                    .getNetworkInterfaces(); en.hasMoreElements();) {
                NetworkInterface intf = en.nextElement();
                for (Enumeration<InetAddress> enumIpAddr = intf
                        .getInetAddresses(); enumIpAddr.hasMoreElements();) {
                    InetAddress inetAddress = enumIpAddr.nextElement();
                    if (!inetAddress.isLoopbackAddress()) {
                        return inetAddress.getHostAddress().toString();
                    }
                }
            }
        } catch (SocketException ex) {
            Log.e("WifiPreference IpAddress", ex.toString());
        }
        return null;
    }

    /**
     * 获取Android本机MAC
     * 
     * @return
     */
    private String getLocalMacAddress() {
        WifiManager wifi = (WifiManager) this.getApplicationContext()
                .getSystemService(Context.WIFI_SERVICE);
        WifiInfo info = wifi.getConnectionInfo();

        return info.getMacAddress();
    }
  1. 图片下载服务类
package com.vincent.org.networkapp.download;

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

import android.content.Context;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.os.AsyncTask;
import android.util.Log;
import android.widget.ImageView;

public class ImageService {

    private static final String TAG = "ImageService";

    private final Context mContext;
    private final ImageView mImageView;

    public ImageService(Context context, ImageView imageView) {
        this.mContext = context;
        this.mImageView = imageView;
    }

    public static Bitmap getImage(ImageView imageView, String pathUrl)
            throws MalformedURLException {

        // 构建url
        URL url = new URL(pathUrl);
        // 打开一个http链接
        Log.i(TAG, "和服务器开始链接");
        DownTask downTaskCase = new DownTask(null, imageView);
        downTaskCase.execute(url);
        return null;
    }

    /**
     * 异步任务下载网络图片数据 必须对网络请求在新建线程中进行,不能在main线程中进行网络请求这些 时间比较多的请求。不然就报这些NetworkOnMainThreadException异常。 这个错误是说你在main线程里面执行网络操作。最新sdk版本是不允许的。(为了避免anr异常出现)。
所以,解决的话,只要另外开个线程,把网络操作放到新线程里面就好啦
     * 
     * @author cindy
     * 
     */
    private static class DownTask extends AsyncTask<URL, Integer, Bitmap> {
        private static final String TAG_DT = "DownTask";
        private final Context mContext;
        private final ImageView mImageView;

        public DownTask(Context context, ImageView imageView) {
            this.mImageView = imageView;
            this.mContext = context;
        }

        @Override
        protected void onPreExecute() {
            // TODO Auto-generated method stub
            super.onPreExecute();
            Log.i(TAG_DT, TAG_DT + "Ready");
        }

        @Override
        protected Bitmap doInBackground(URL... params) {
            // TODO Auto-generated method stub
            Log.i(TAG_DT, TAG_DT + "begin");
            HttpURLConnection urlConnection;
            try {
                urlConnection = (HttpURLConnection) params[0].openConnection();
                urlConnection.setConnectTimeout(500);// 超时时间
                urlConnection.setRequestMethod("GET");// 请求方法
                if (urlConnection.getResponseCode() == 200) {
                    Log.i(TAG_DT, "和服务器建立了链接");
                    // 获得了http的正确响应码后,返回一个输入流
                    InputStream ins = urlConnection.getInputStream();
                    Bitmap bitmap = BitmapFactory.decodeStream(ins);
                    return bitmap;
                }
            } catch (IOException e) {
                // TODO Auto-generated catch block
                e.printStackTrace();
            }

            return null;
        }

        @Override
        protected void onPostExecute(Bitmap result) {
            // TODO Auto-generated method stub
            Log.i(TAG_DT, TAG_DT + "complete");
            super.onPostExecute(result);
            // 把图像更新到ui
            mImageView.setImageBitmap(result);
        }

    }
}

布局文件


<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:paddingBottom="@dimen/activity_vertical_margin"
    android:paddingLeft="@dimen/activity_horizontal_margin"
    android:paddingRight="@dimen/activity_horizontal_margin"
    android:paddingTop="@dimen/activity_vertical_margin"
    tools:context="com.vincent.org.networkapp.DownLoadImageShowActivity" >

    <TextView
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="@string/path" 
        android:id="@+id/path"/>
<!-- 将下载资源链接直接写进来-->
    <EditText
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:text="http://192.168.44.119:8080/ServierWebForSimple/vincent.png"
        android:id="@+id/pathEditText"
        android:layout_below="@id/path" />

    <Button
        android:id="@+id/startDownImage"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:layout_alignLeft="@+id/pathEditText"
        android:layout_below="@+id/pathEditText"
        android:layout_marginTop="18dp"
        android:text="@string/startDownImage" 
        android:onClick="startDownImage"/>

    <ImageView
        android:id="@+id/show"
        android:layout_width="match_parent"
        android:layout_height="match_parent"

        android:layout_below="@+id/startDownImage" />

</RelativeLayout>

增加网络访问权限

 <uses-permission android:name="android.permission.INTERNET" />
    <uses-permission android:name="android.permission.ACCESS_WIFI_STATE"/>
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值