20160414_jeffrey - silenceuncrio/diary GitHub Wiki

Index

  • 0745 - Android HttpUrlConnection HttpClient
  • 0930 - android.os.NetworkOnMainThreadException AsyncTask
  • 1015 - Android HttpUrlConnection HttpClient AsyncTask
  • 1130 - 成功突破 記錄
  • 1300 - 回傳 json 處理
  • 1415 - How to parse JSON data in Android
  • 1540 - Android POST and GET Request using HttpURLConnection Tutorial
  • 1555 - Android Httpurlconnection Post and Get Request Tutorial

0745

今天從 详细讲解Android的网络通信(HttpUrlConnection和HttpClient) 這篇開始看

0930

遇到 android.os.NetworkOnMainThreadException 的問題
不過網路已經有一堆答案了

看到 aaron 的 app 用的是 AsyncTask

趕緊看吧... 我不知道的東西還一堆呢...

早上連基本的 hello cgi 都出錯了
因為我把 html header 忘了

#include <stdio.h>

int main() {
    printf("Content-Type: text/html\r\n\r\n");
    printf("hello world");
    return 0;
}

不能少的關鍵敘述 printf("Content-Type: text/html\r\n\r\n");
不然 client 端會以為沒有回應

1015

直接找個現成範例

Android網络編程 HttpUrlConnection HttpClient AsyncTask

1130

終於成功突破了
趕緊記錄一下

Android Virtual Device - UseAsyncTask
image

AndroidManifest.xml

<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
          package="com.bignerdranch.android.useasynctask">

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

    <application
        android:allowBackup="true"
        android:icon="@mipmap/ic_launcher"
        android:label="@string/app_name"
        android:supportsRtl="true"
        android:theme="@style/AppTheme">
        <activity android:name=".MainActivity">
            <intent-filter>
                <action android:name="android.intent.action.MAIN"/>

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

</manifest>

active_main.xml

<?xml version="1.0" encoding="utf-8"?>
<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">

    <TextView
        android:text="開眼電影"
        android:background="#1c9439"
        android:textSize="24sp"
        android:textColor="#fff"
        android:layout_marginTop="5dp"
        android:layout_marginBottom="10dp"
        android:gravity="center"
        android:layout_marginLeft="10dp"
        android:layout_marginRight="10dp"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"/>

    <ImageView
        android:id="@+id/movie_image"
        android:gravity="center"
        android:background="#ffcc"
        android:layout_margin="3dp"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"/>

</LinearLayout>

MainActivity.java

package com.bignerdranch.android.useasynctask;

import android.app.ProgressDialog;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.os.AsyncTask;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.widget.ImageView;

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

public class MainActivity extends AppCompatActivity {

    private ImageView imageView;

    // 圖片地址
    private final String url = "http://www.photowant.com/photo101/fhen02381991/pl_fhen02381991_0018.jpg";
    //顯示進度
    private ProgressDialog pDialog;


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

        //用來顯示進度
        pDialog = new ProgressDialog(this);
        pDialog.setProgressStyle(ProgressDialog.STYLE_HORIZONTAL);
        pDialog.setMessage("Loading...");
        pDialog.setMax(100);

        imageView = (ImageView) findViewById(R.id.movie_image);

        //執行 Task
        new ImageDownloadTask().execute(url);

    }



    public class ImageDownloadTask extends AsyncTask<String,Integer,Bitmap> {

        @Override
        protected void onPreExecute() {
            super.onPreExecute();
            pDialog.show();
        }

        @Override
        protected Bitmap doInBackground(String... urls) {

            HttpURLConnection connection = null;

            Bitmap bitmap = null;

            try {

                URL url = new URL(urls[0]);

                connection = (HttpURLConnection) url.openConnection();

                InputStream in = new BufferedInputStream(connection.getInputStream());

                bitmap = BitmapFactory.decodeStream(in);

                //獲取文件流大小, 用於更新進度
                int length = connection.getContentLength();
                int len = 0, total_length = 0, value = 0;
                byte[] data = new byte[1024];

                while ( (len = in.read(data)) != -1) {
                    total_length += len;
                    value = (int)( (total_length/(float)length)*100);
                    //調用update函數, 更新進度
                    publishProgress(value);

                }


            } catch (IOException e) {
                e.printStackTrace();
            } finally {
                if (connection != null) {
                    connection.disconnect();
                }
            }

            return bitmap;

        }

        @Override
        protected void onProgressUpdate(Integer... values) {
            super.onProgressUpdate(values);
            pDialog.setProgress(values[0]);
        }

        @Override
        protected void onPostExecute(Bitmap bitmap) {
            if (pDialog != null) {
                pDialog.dismiss();
            }
            pDialog = null;
            // 將Bitmap填充進ImageView
            imageView.setImageBitmap(bitmap);
        }

    }

}

1300

來找一下回傳 json 怎麼來處理

How to parse JSON data in Android

1415

How to parse JSON data in Android 這篇文章寫得極好

程式也非常清楚
不賣弄
不做多餘的事

該部落格還有很多範例... 挖到寶了

1540

改來看怎麼做 post

Android POST and GET Request using HttpURLConnection Tutorial

直接下載範例 run run 看

這個範例雖然能跑
不過 coding 內容跟上一個比起來就不是我喜歡的了

1555

明天來看這一篇 - Android Httpurlconnection Post and Get Request Tutorial

⚠️ **GitHub.com Fallback** ⚠️