android 请求网络数据 HttpURLConnection
import java.io.InputStream;
import java.net.HttpURLConnection;
import java.net.URL;
import android.app.Activity;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.os.Bundle;
import android.view.View;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.TextView;
public class MainActivity extends Activity {
private EditText et_path;
private TextView tv_context;
private ImageView iv;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
et_path = (EditText) findViewById(R.id.et_path);
iv = (ImageView) findViewById(R.id.iv_imge);
}
public void click(View v) {
new Thread() {
public void run() {
try {
String path = et_path.getText().toString().trim();
URL url = new URL(path);
HttpURLConnection conn = (HttpURLConnection) url.openConnection();
conn.setRequestMethod("GET");
conn.setConnectTimeout(5000);
int code = conn.getResponseCode();
if (code == 200) {
InputStream in = conn.getInputStream();
final Bitmap bitmap = BitmapFactory.decodeStream(in);
runOnUiThread(new Runnable() {
public void run() {
iv.setImageBitmap(bitmap);
}
});
}
} catch (Exception e) {
e.printStackTrace();
}
}
}.start();
}
}
import java.io.ByteArrayOutputStream;
import java.io.InputStream;
public class StreamTools {
public static String parserInputStream(InputStream in){
try {
ByteArrayOutputStream baso = new ByteArrayOutputStream();
int len = 0;
byte buffer[] = new byte[1024];
while((len = in.read(buffer))!=-1){
baso.write(buffer, 0, len);
}
String content = new String(baso.toByteArray());
return content;
} catch (Exception e) {
e.printStackTrace();
return null;
}
}
}