java攻城狮之路(Android篇)--与服务器交互

一、图片查看器和网页源码查看器

在输入地址的是不能输入127.0.0.1 或者是 localhost.
ScrollView :可以看成一个滚轴 可以去包裹很多的控件在里面

练习1(图片查看器):

package com.shellway.imagelooker;

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

import org.apache.http.conn.ConnectTimeoutException;

import android.support.v7.app.ActionBarActivity;
import android.annotation.SuppressLint;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.os.Bundle;
import android.os.StrictMode;
import android.view.View;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.Toast;

public class MainActivity extends ActionBarActivity {

    private EditText path;
    private ImageView iv;

    @SuppressLint("NewApi")
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        
        path = (EditText) findViewById(R.id.et_path);
        iv = (ImageView) findViewById(R.id.iv_image);
        StrictMode.ThreadPolicy policy=new StrictMode.ThreadPolicy.Builder().permitAll().build();
        StrictMode.setThreadPolicy(policy);
    }
    public void onLook(View view){
        String spath = path.getText().toString();
        System.out.println(spath);
        if(spath.equals("")){
            Toast.makeText(this, "输入的地址为空", Toast.LENGTH_SHORT).show();
        }else {
            try {
                URL url = new URL(spath);
                HttpURLConnection conn = (HttpURLConnection) url.openConnection();
                conn.setRequestMethod("GET");
                conn.setConnectTimeout(5000);
                
                if(conn.getResponseCode() == 200){
                    InputStream is = conn.getInputStream();
                    Bitmap bm = BitmapFactory.decodeStream(is);
                    if(bm == null){
                        Toast.makeText(this, "获取的图片流为空", Toast.LENGTH_SHORT).show();
                    }else{
                        iv.setImageBitmap(bm);
                    }
                }else{
                    Toast.makeText(this, "输入的路径不存在", Toast.LENGTH_SHORT).show();
            }
                
            } catch (Exception e) {
                e.printStackTrace();
                if(e instanceof MalformedURLException){
                    Toast.makeText(this, "输入的路径格式错误", Toast.LENGTH_SHORT).show();
                }else if(e instanceof ConnectTimeoutException){
                    Toast.makeText(this, "连接超时错误", Toast.LENGTH_SHORT).show();
                }else if(e instanceof IOException){
                    Toast.makeText(this, "获取数据错误", Toast.LENGTH_SHORT).show();
                }else{
                    Toast.makeText(this, "未知错误", Toast.LENGTH_SHORT).show();
                }
            } 
        }
    }
}
MainActivity.java
<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
    package="com.shellway.imagelooker"
    android:versionCode="1"
    android:versionName="1.0" >

    <uses-sdk
        android:minSdkVersion="8"
        android:targetSdkVersion="21" />
    <uses-permission android:name="android.permission.INTERNET"/>

    <application
        android:allowBackup="true"
        android:icon="@drawable/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

练习2(网页源码查看器):

package com.shellway.htmllooker;

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

import org.apache.http.client.utils.URIUtils;

import android.support.v7.app.ActionBarActivity;
import android.text.TextUtils;
import android.annotation.SuppressLint;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.os.StrictMode;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.webkit.URLUtil;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.TextView;
import android.widget.Toast;

public class MainActivity extends ActionBarActivity {

    protected static final int CHANGE_UI = 1;
    private EditText et_path;
    private TextView iv;
    private String path;
//    private Handler handler;
    
    @SuppressLint("NewApi")
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        et_path = (EditText) findViewById(R.id.et_path);
        iv = (TextView) findViewById(R.id.iv_image);
/*        handler = new Handler(){
            public void handleMessage(Message msg) {
                if(msg.what == CHANGE_UI){
                String s = (String) msg.obj;
                iv.setText(s);
                }
            };
        };*/
        StrictMode.ThreadPolicy policy=new StrictMode.ThreadPolicy.Builder().permitAll().build();
        StrictMode.setThreadPolicy(policy);
    }
    public void onLook(View view){
        path = et_path.getText().toString().trim();
        if(TextUtils.isEmpty(path)){
            Toast.makeText(MainActivity.this, "您输入的地址为空", Toast.LENGTH_SHORT).show();
        }else{
        // new Thread(){
        //     public void run() {
                    try {
                        URL url = new URL(path);
                        HttpURLConnection conn = (HttpURLConnection) url.openConnection();
                        conn.setRequestMethod("GET");
                        conn.setConnectTimeout(5000);
                        if(conn.getResponseCode()==200){
                            InputStream is = conn.getInputStream();
                            ByteArrayOutputStream bos = new ByteArrayOutputStream();
                            byte[] buffer = new byte[1024];
                            int len=0 ;
                            while((len = is.read(buffer))!=-1){
                                bos.write(buffer, 0, len);
                            }
                            String text =bos.toString();
                            bos.close();
                            is.close();
                        //    Message msg = new Message();
                        //    msg.what = CHANGE_UI;
                        //    msg.obj = text;
                        //    handler.sendMessage(msg);
                            iv.setText(text);
                        }
                    } catch (Exception e) {
                        e.printStackTrace();
                    }
        //     };
    //     }.start();
        }
    }
}
MainActivity.java
<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
    package="com.shellway.htmllooker"
    android:versionCode="1"
    android:versionName="1.0" >

    <uses-sdk
        android:minSdkVersion="8"
        android:targetSdkVersion="21" />
    <uses-permission android:name="android.permission.INTERNET"/>

    <application
        android:allowBackup="true"
        android:icon="@drawable/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

二、网易新闻客户端

1.对抓取的数据进行一个描述,我们用的是xml文件来进行描述,如:
<HeaderNews>
<HeaderNew>
<image>httP://192.168.1.101:8080/web/a.jpg<image>
<title>女子花3万相亲</title>
<content>婚介所向其介绍男友后消失<content>
<count>44跟帖</count>
</HeaderNew>
</HeaderNews>

首先数据是动态的。我们可以用servlet(查询数据库里面的数据) - 然后传递数据 通过request(转发)--> jsp 显示

findViewById() 直接使用是在我们的activity的布局里面去查找

注意:流被使用过之后,就不能再次使用。


json 轻量级的 数组 [{image:"httP://192.168.1.101:8080/web/a.jpg",title:"",content:"",count:""},{}]

ISO-8859-1 utf-8

get请求:把要提交的数据直接添加到路径的后面,
由于服务器对请求路径的长度是有限制的。最大不能超过4k,截取数据导致数据不完整。

post请求:

android系统引入了一个三方的框架 HttpClient 他就是对http协议的一个封装


文件上传:我们使用三方开源框架upload

在android端我们也使用HttpClient来实现文件的上传:HttpClient的版本必须在3.0之上。

电话归属地查询:
android server(webservice)

webservice:网络上的api

Bitmap BitmapFactory
ScrollView

Http : URL HttpURLConnection conn 联网权限

xml
json

http get /post

HttpClient

文件上传

 

注意啦:本页还没完善,后续会更新。。。。。。

 

郑重声明:本站内容如果来自互联网及其他传播媒体,其版权均属原媒体及文章作者所有。转载目的在于传递更多信息及用于网络分享,并不代表本站赞同其观点和对其真实性负责,也不构成任何其他建议。