Android网络获取服务器文字及图片

package com.example.lenovo.myapplication;


        import android.app.Activity;
        import android.graphics.Bitmap;
        import android.graphics.BitmapFactory;
        import android.os.Bundle;
        import android.os.Handler;
        import android.os.Message;
        import android.util.Log;
        import android.widget.ImageView;
        import android.widget.TextView;
        import android.widget.Toast;

        import org.json.JSONObject;

        import java.io.BufferedReader;
        import java.io.InputStream;
        import java.io.InputStreamReader;
        import java.lang.ref.WeakReference;
        import java.net.HttpURLConnection;
        import java.net.URL;

public class MainActivity extends Activity {

    class MyHandler extends Handler {
        WeakReference<MainActivity> mActivityReference;

        MyHandler(MainActivity activity) {
            mActivityReference= new WeakReference<MainActivity>(activity);
        }

        @Override
        public void handleMessage(Message msg) {
            MainActivity activity = mActivityReference.get();

            switch(msg.what) {
                case 123:
                    activity.showNetText();
                    break;
                case 456:
                    activity.showNetFail();
                    break;

                default:
                    break;
            }

            super.handleMessage(msg);

        }
    };

    MyHandler handler=new MyHandler(this);

    TextView net_tv;
    String netTextStr="";

    String  imgurl="http://192.168.42.85:8080/imgs/t.png";

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);

        net_tv=(TextView)findViewById(R.id.net_text_tv);
        ImageView iv=(ImageView)findViewById(R.id.net_img_iv);
        loadOrgBitmapByUrlAsync(iv,imgurl);
        //accessNet();
    }

    private void showNetText(){
        net_tv.setText(netTextStr);
    }

    private void showNetFail(){
        Toast.makeText(this,"net operation failed",Toast.LENGTH_SHORT).show();
    }

    private boolean parseJson(String str){
        try {
            JSONObject jsonObject=new JSONObject(str);
            int retc=jsonObject.getInt("ret_code");
            if(retc==0){
                netTextStr=jsonObject.getString("ret_str");
            }
        }catch (Exception e){
            e.printStackTrace();
            return false;
        }
        return true;
    }
    private String getServerUrlParam(){
        String url="http://192.168.42.85:8080/test.jsp";
        return url;
    }

    private void getServerData(String url){
        try {
            URL myUrl = new URL(url);
            HttpURLConnection myconn = (HttpURLConnection) myUrl.openConnection();
            myconn.setRequestProperty("User-Agent", "Internet Explorer");
            myconn.setConnectTimeout(5000);
            myconn.setReadTimeout(5000);
            InputStream stream = myconn.getInputStream();
            BufferedReader br = new BufferedReader(new InputStreamReader(stream, "UTF-8"));
            String line = null;
            StringBuffer sb = new StringBuffer();
            while ((line = br.readLine()) != null) {
                sb.append(line);
            }
            stream.close();

            String str = sb.toString();//返回的字符串
            Log.v("test","server:"+str);

            if(parseJson(str)) {
                handler.sendEmptyMessage(123);
            }else {
                handler.sendEmptyMessage(456);
            }

        }catch (Exception e){
            e.printStackTrace();
            handler.sendEmptyMessage(456);
        }
    }
    private void accessNet(){
        new Thread(){

            @Override
            public void run()
            {
                getServerData(getServerUrlParam());
            }

        }.start();
    }

    //从网络地址获取图像文件并构建Bitmap对象
    public Bitmap getOrgBitmapByUrl(String url)
    {
        try
        {
            URL myUrl=new URL(url);
            return BitmapFactory.decodeStream(myUrl.openStream());
        }catch(Exception e)
        {
            return null;
        }

    }

    public void loadOrgBitmapByUrlAsync(final ImageView iv, final String url)
    {
        //线程加载完图片对象后的处理
        final Handler handler=new Handler(){
            public void handleMessage(Message message) {

                if(message==null)
                    return;
                iv.setImageBitmap((Bitmap)message.obj);
            }
        };
        //启动线程
        new Thread() {
            @Override
            public void run() {

                //加载图片
                Bitmap bmp = getOrgBitmapByUrl(url);

                //向处理线程发送消息
                Message message = handler.obtainMessage(0, bmp);
                handler.sendMessage(message);
            }

        }.start();
    }

}

.xml文件:


<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:orientation="vertical"
    android:gravity="center"
    >

    <TextView
        android:id="@+id/net_text_tv"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="Hello World!"
        />
    <ImageView
        android:id="@+id/net_img_iv"
        android:layout_width="100dp"
        android:layout_height="100dp"
        />
LinearLayout>

AndroidManifest.xml:


<manifest xmlns:android="http://schemas.android.com/apk/res/android"
    package="com.example.lenovo.myapplication" >
    <uses-permission android:name="android.permission.INTERNET">uses-permission>
    <application
        android:allowBackup="true"
        android:icon="@mipmap/ic_launcher"
        android:label="@string/app_name"
        android:theme="@style/AppTheme" >
        <activity
            android:name=".MainActivity"
            android:label="@string/app_name" >
            <intent-filter>
                <action android:name="android.intent.action.MAIN" />

                <category android:name="android.intent.category.LAUNCHER" />
            intent-filter>
        activity>
    application>

manifest>

这个是局域网的向服务器获得图片以及文字的方法,一定要在AndroidManifest.xml加上网络权限,这个应该覆盖了网络的大部分

你可能感兴趣的:(android,服务器,运维,1024程序员节)