本段我通过一个例子展现如果从服务器段接受数据。

案例一: 通过图片URL查看图片

首先是一个简单的界面: res/layout/activity_main.xml

<LinearLayout 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:orientation="vertical"
    tools:context=".MainActivity" >

    <TextView
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="@string/image_path_label" />
    
    <EditText 
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:inputType="text"
        android:text="@string/default_path"
        android:id="@+id/image_path_view" />
    
    <Button
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="@string/view_btn_lavel"
        android:id="@+id/view_btn_view" />
    
    <ImageView 
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:id="@+id/image_view" />

</LinearLayout>

InternetUtil.java

package com.lk.util;

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

public class InternetUtil {

    /**
     * 通过图片URL来获取图片数据
     * @param imagePath
     * @return
     * @throws Exception
     */
    public static byte[] getDataByPath(String imagePath) throws Exception {
        byte[] result = null;
        URL url = new URL(imagePath);
        HttpURLConnection connect = (HttpURLConnection) url.openConnection();  //获取一个HTTP协议的连接
        connect.setConnectTimeout(5000);  //设置连接超时时间为5000ms
        connect.setRequestMethod("GET");  //设置请求方式
        int responseCode = connect.getResponseCode();
        if(responseCode == 200) {
            //success
            InputStream is = connect.getInputStream();
            result = getDataFromStream(is);
            is.close();
        }
        
        return result;
    }
    
    private static byte[] getDataFromStream(InputStream is) throws IOException {
        ByteArrayOutputStream outputStream = new ByteArrayOutputStream();
        byte[] result = null;
        try {
            byte[] buffer = new byte[1024];
            int length = 0;
            while((length = is.read(buffer)) != -1) {
                outputStream.write(buffer, 0, length);
            }
            result = outputStream.toByteArray();
        } finally {
            if(outputStream != null) {
                outputStream.close();
            }
        }
        return result;
    }

    /**
     * 通过URL来获取网页源码
     * @param path
     * @return
     * @throws Exception
     */
    public static String getSourceCodeByPath(String path) throws Exception {
        String result = "";
        URL url = new URL(path);
        HttpURLConnection connection = (HttpURLConnection) url.openConnection();
        connection.setConnectTimeout(5000);
        connection.setRequestMethod("GET");
        int statusCode = connection.getResponseCode();
        if(statusCode == 200) {
            InputStream is = connection.getInputStream();
            byte[] data = getDataFromStream(is);
            result = new String(data, "UTF-8");
            is.close();
        }
        return result;
    }

}

MainActivity.java

package com.lk.imageviewer;

import com.lk.util.InternetUtil;

import android.os.Bundle;
import android.app.Activity;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.view.Menu;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.Toast;

public class MainActivity extends Activity {
    private EditText imagePathView;
    private ImageView imageView;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        
        imagePathView = (EditText) findViewById(R.id.image_path_view);
        imageView = (ImageView) findViewById(R.id.image_view);
        Button viewBtn = (Button)findViewById(R.id.view_btn_view);
        viewBtn.setOnClickListener(new OnClickListener() {
            @Override
            public void onClick(View v) {
                String imagePath = imagePathView.getText().toString();
                try {
                    byte[] imageData = InternetUtil.getDataByPath(imagePath);
                    Bitmap bm = BitmapFactory.decodeByteArray(imageData, 0, imageData.length);
                    imageView.setImageBitmap(bm);
                } catch (Exception e) {
                    e.printStackTrace();
                    Toast.makeText(getApplicationContext(), R.string.error, Toast.LENGTH_SHORT).show();
                }
            }
        });
    }

}

因为连接网络要流量,肯定会产生费用,所以我在清单文件中申请权限

<uses-permission android:name="android.permission.INTERNET"/>

 

然后就可以进行测试了。

 

 

 

posted on 2014-03-27 21:00  寒岁青松  阅读(182)  评论(0)    收藏  举报