package com.yanjun;
import com.yanjun.getImage.GetHTML;
import android.app.Activity;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.EditText;
import android.widget.TextView;
import android.widget.Toast;
/**
* 經過網絡獲取圖片
* @author YanJun
*<uses-permission android:name="android.permission.INTERNET"></uses-permission>
*/
public
class MainActivity
extends Activity {
private
static
final String TAG =
"MainActivity";
EditText htmlEditText =
null ;
Button button ;
TextView htmlTextView =
null;
@Override
public
void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
htmlTextView = (TextView) findViewById(R.id.textView_html);
htmlEditText = (EditText) findViewById(R.id.editText_html);
button = (Button) findViewById(R.id.button_get);
button.setOnClickListener(
new OnClickListener() {
public
void onClick(View v) {
// TODO Auto-generated method stub
String Url = htmlEditText.getText().toString();
try {
htmlTextView.setText(GetHTML.getHtml(Url));
}
catch (Exception e) {
Toast
.makeText(MainActivity.
this,
"連接延時",
Toast.LENGTH_LONG).show();
Log.e(TAG, e.toString());
}
}
});
}
}
package com.yanjun.getImage;
import java.io.InputStream;
import java.net.HttpURLConnection;
import java.net.URL;
public
class GetHTML {
/**
* 獲取路徑方法
*
* @param path 路徑
* @return
* @throws Exception
*/
public
static String getHtml(String path)
throws Exception {
// 從網絡上獲取html--URL對象用來封裝路徑
URL url =
new URL(path);
// 打開路徑連接---獲得HttpURLConnection對象
HttpURLConnection httpURLConnection = (HttpURLConnection) url
.openConnection();
// 經過HTTP協議請求網絡HTML---設置請求方式:get/post
httpURLConnection.setRequestMethod(
"GET");
// 設置鏈接超時
httpURLConnection.setConnectTimeout(5 * 1000);
// 從外界想手機應用內傳遞數據----經過輸入流獲取HTML數據
InputStream inputStream = httpURLConnection.getInputStream();
byte[] data = StreamTool.readInputStream(inputStream);
// 從輸入流中獲取HTML的二進制數據----readInputStream()
String html =
new String(data);
return html;
}
}
package com.yanjun.getImage;
import java.io.ByteArrayOutputStream;
import java.io.InputStream;
public
class StreamTool {
/**從輸入流獲取數據
* @param inSream 輸入流
* @return
* @throws Exception
*/
public
static
byte[] readInputStream(InputStream inSream)
throws Exception {
ByteArrayOutputStream byteArrayOutputStream =
new ByteArrayOutputStream();
// 定義一個緩衝區
byte[] buffer =
new
byte[1024];
int len = 0;
// 不斷的從流裏讀取數據---while循環---nSream.read(buffer)表示從流裏讀取數據到緩衝區
// 讀取到末尾時,返回值是-1;
while ((len = inSream.read(buffer)) != -1) {
// 將緩衝區的數據寫到輸出流中
byteArrayOutputStream.write(buffer, 0, len);
}
inSream.close();
return byteArrayOutputStream.toByteArray(); } }