实践是知识的母亲,知识是生活的明灯。这篇文章主要讲述[Android基础]Android中使用HttpURLConnection相关的知识,希望能为你提供帮助。
HttpURLConnection继承了URLConnection,因此也能够向指定站点发送GET请求、POST请求。它在URLConnetion的基础上提供了例如以下便捷的方法。
【[Android基础]Android中使用HttpURLConnection】int getResponseCode():获取server的响应代码。
String getResponseMessage():获取server的訪问信息。
String getRequestMethod():获取发送请求的方法。
void setRequestMethod(String method):设置发送请求的方法。
我们通过两个样例来体会一下:
一、将站点的内容显示在界面上:
1、创建一个WebView
<
WebView
android:id="@+id/webView"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:layout_alignParentLeft="true"
android:layout_alignParentTop="true" />
2、MainActivity.java
public class MainActivity extends Activity {private WebView webview;
//通过Handler在子线程更新主界面的UI
private Handler handler = new Handler();
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
webview = (WebView) findViewById(R.id.webView);
new HttpThread("http://www.sina.com", webview, handler).start();
}
}
3、创建一个子线程
public class HttpThread extends Thread {
private String url;
private WebView webview;
private Handler handler;
//通过构造函数传三个參数
public HttpThread(String url, WebView webView, Handler handler) {
this.url = url;
this.webview = webView;
this.handler = handler;
}
}
@Override
public void run() {
try {
URL httpUri = new URL(url);
HttpURLConnection conn = (HttpURLConnection) httpUri.openConnection();
conn.setReadTimeout(5000);
conn.setRequestMethod("GET");
final StringBuffer sb = new StringBuffer();
BufferedReader reader = new BufferedReader(new InputStreamReader(conn.getInputStream()));
String str;
while((str = reader.readLine()) != null)
{
sb.append(str);
}
handler.post(new Runnable() {@Override
public void run() {
//将数据载入到webview中
webview.loadData(sb.toString(), "text/html;
charset=utf-8", null);
}
});
} catch (MalformedURLException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
4、在AndroidManifest中加入权限:
android:name=”android.permission.INTERNET”
二、依据URL地址下载一张图片
1、创建一个webview
<
ImageView
android:id="@+id/imageView1"
android:layout_width="match_parent"
android:layout_height="match_parent"/>
2、MainActivity.java
public class MainActivity extends Activity {private Handler handler = new Handler();
private ImageView imageView;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
imageView = (ImageView) findViewById(R.id.imageView1);
newHttpThread("http://img5.duitang.com/uploads/item/201410/23/20141023211631_VKmfz.jpeg", imageView, handler).start();
}
3、创建一个子线程
public class HttpThread extends Thread {
private String url;
private Handler handler;
private ImageView imageView;
public HttpThread(String url, ImageView imageView, Handler handler) {
this.url = url;
this.imageView = imageView;
this.handler = handler;
}
@Override
public void run() {
try {
URL httpUri = new URL(url);
HttpURLConnection conn = (HttpURLConnection) httpUri.openConnection();
conn.setReadTimeout(5000);
conn.setRequestMethod("GET");
//设置能够读取到输入流
conn.setDoInput(true);
InputStream in = conn.getInputStream();
FileOutputStream out = null;
String fileName = String.valueOf(System.currentTimeMillis());
File downloadFile = null;
if(Environment.getExternalStorageState().equals(Environment.MEDIA_MOUNTED))
{
//获得SDcard的文件夹文件
File parent = Environment.getExternalStorageDirectory();
downloadFile = new File(parent, fileName);
out = new FileOutputStream(downloadFile);
}
//缓冲区
byte[] b = new byte[2 * 1024];
int len;
if(out != null)
{
while((len = in.read(b)) != -1)
{
out.write(b, 0, len);
}
}
final Bitmap bitmap = BitmapFactory.decodeFile(downloadFile.getAbsolutePath());
handler.post(new Runnable() {@Override
public void run() {
imageView.setImageBitmap(bitmap);
}
});
} catch (MalformedURLException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
4、在AndroidManifest中加入权限:
android:name=”android.permission.WRITE_EXTERNAL_STORAGE”
这样下载的图片就显示在界面上了。
推荐阅读
- Android5 Zygote 与 SystemServer 启动流程分析
- Android-删除指定包名的App
- Android中的Telephony学习笔记
- Android Studio - 第四十五期 Gradle manifestPlaceholders
- 如何在macOS上安装CodeIgniter
- 如何在MacOS上安装CakePHP
- 如何在MacOS上安装BlueFish
- 如何在MacOS上安装XAMPP
- 如何在MacOS上安装Vim