Android與Tomcat伺服器的應用

來源:互聯網
上載者:User

標籤:線程   public   ons   override   arc   timeout   his   actor   print   

在Tomcat的根目錄中放入一張圖片...webapps\ROOT\people,jpg,利用手機和伺服器互動j擷取這個圖片,案頭布局就是簡單的線性布局,代碼:
<TextView
android:textSize="25dp"
android:text="伺服器圖片的地址:"
android:layout_width="wrap_content"
android:layout_height="wrap_content" />
<EditText
android:id="@+id/et_pct"
android:layout_width="match_parent"
android:layout_height="wrap_content"/>

<Button
android:id="@+id/btn_search"
android:layout_width="match_parent"
android:layout_height="wrap_content"/>

<ImageView
android:id="@+id/iv_pic"
android:layout_width="match_parent"
android:layout_height="match_parent"/>
通過輸入伺服器位址,點擊按鈕就可以實現查看Tomcat的圖片:
主要代碼:
Handler mHandler = new Handler() {
public void handleMessage(android.os.Message msg) {
IvPic.setImageBitmap(mBitmap1);
}
};

private void initConnnect() {
new Thread(new Runnable() {
@Override
public void run() {
String url_path = EtPct.getText().toString().trim();
if (TextUtils.isEmpty(url_path)){
Toast.makeText(MainActivity.this, "請輸入圖片網址", Toast.LENGTH_SHORT).show();
}else{
try {
URL url = new URL(url_path);
HttpURLConnection urlConnection = (HttpURLConnection) url.openConnection();
urlConnection.setRequestMethod("GET");
urlConnection.setConnectTimeout(5000);
if (urlConnection.getResponseCode()==200) {
InputStream inputStream = urlConnection.getInputStream();
mBitmap1 = BitmapFactory.decodeStream(inputStream);
if (mBitmap1 == null) {
Toast.makeText(MainActivity.this, "圖片擷取錯誤", Toast.LENGTH_SHORT).show();
} else {
mHandler.sendEmptyMessage(0);
}
}
} catch (Exception e) {
e.printStackTrace();
}

}
}
}).start();
}


點擊按鈕觸發initConnnect()這個方法,由於請求伺服器比較耗時,開啟子線程進行請求。
最後別忘了加入許可權:<uses-permission android:name="android.permission.INTERNET"/>
如果還無法訪問,那就是你電腦防火牆開了,把防火牆關了,就可以了。:

 

 

注意:IP地址要用電腦IP地址,不能用10.0.2.2.
。這個就可以實現簡單訪問伺服器圖片。
如果引用Xutils架構,代碼則更加方便:
mBitmapUtils = new BitmapUtils(MainActivity.this);
String url_path = EtPct.getText().toString().trim();

mBitmapUtils.display(IvPic,url_path);
這樣就可以實現訪問了。
但是引用Xutils需要加入許可權:
<uses-permission android:name="android.permission.INTERNET"/>
<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE"/>

引入這個庫就行:

 

就可以了。是不是還是感覺Xutils比較方便。

Android與Tomcat伺服器的應用

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.