2.设置头信息之后获取响应码,如果成功返回 200 即可从 HttpURLConnection 中获取输入流读取数据
<uses-permission android:name="android.permission.INTERNET" />
例1:
public void click(View view) {
new Thread() {
@Override
public void run() {
try {
String path = etUrl.getText().toString();
URL url = new URL(path);
HttpURLConnection conn = (HttpURLConnection) url.openConnection();
conn.setConnectTimeout(5000);
int code = conn.getResponseCode();
if (code == 200) { // 获取响应码
InputStream is = conn.getInputStream();
ByteArrayOutputStream bos = new ByteArrayOutputStream();
byte[] buffer = new byte[8192];
int len = -1;
while ((len = is.read(buffer)) != -1) {
bos.write(buffer, 0, len);
}
is.close();
bos.close();
byte[] data = bos.toByteArray();
final String text = new String(data);
runOnUiThread(new Runnable() {
@Override
public void run() {
tvContent.setText(text);
}
});
}
conn.disconnect();
throw new NetworkErrorException("网络错误:"+code);
} catch (Exception e) {
e.printStackTrace();
}
}
}.start();
}
2. 使用ayscHttpClient(使用前需在github上下载相关源码)
AsyncHttpClient client = new AsyncHttpClient();
client.get(etUrl.getText().toString(), new TextHttpResponseHandler() {
@Override
public void onFailure(int statusCode, Header[] headers,
String responseString, Throwable throwable) {
System.out.println(statusCode);
}
@Override
public void onSuccess(int statusCode, Header[] headers,
String responseString) {
System.out.println(statusCode);
tvContent.setText(responseString);
}
});
//3.使用asyncHttpClient获取图片
AsyncHttpClient client = new AsyncHttpClient();
client.get(etUrl.getText().toString(), new AsyncHttpResponseHandler() {
@Override
public void onSuccess(int statusCode, Header[] headers, byte[] responseBody) {
Bitmap bitmap = BitmapFactory.decodeByteArray(responseBody, 0, responseBody.length);
iv_content.setImageBitmap(bitmap);
}
@Override
public void onFailure(int statusCode, Header[] headers,
byte[] responseBody, Throwable error) {
}
});