1.HttpURLConnection
HttpURLConnection的使用步骤
创建一个URL对象: URL url = new URL(https://www.baidu.com);
调用URL对象的openConnection( )来获取HttpURLConnection对象实例: HttpURLConnection conn = (HttpURLConnection) url.openConnection();
设置HTTP请求使用的方法:GET或者POST,或者其他请求方式比如:PUT conn.setRequestMethod("GET");
设置连接超时,读取超时的毫秒数,以及服务器希望得到的一些消息头 conn.setConnectTimeout(6*1000); conn.setReadTimeout(6 * 1000);
调用getInputStream()方法获得服务器返回的输入流,然后输入流进行读取了 InputStream in = conn.getInputStream();
最后调用disconnect()方法将HTTP连接关掉 conn.disconnect();
实例:
工具类:
StreamTool.java:
/**
* Created by Jay on 2015/9/7 0007.
*/
public class StreamTool {
//从流中读取数据
public static byte[] read(InputStream inStream) throws Exception{
ByteArrayOutputStream outStream = new ByteArrayOutputStream();
byte[] buffer = new byte[1024];
int len = 0;
while((len = inStream.read(buffer)) != -1)
{
outStream.write(buffer,0,len);
}
inStream.close();
return outStream.toByteArray();
}
}
布局代码
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical">
<TextView
android:id="@+id/txtMenu"
android:layout_width="match_parent"
android:layout_height="48dp"
android:background="#4EA9E9"
android:clickable="true"
android:gravity="center"
android:text="长按我,加载菜单"
android:textSize="20sp" />
<ImageView
android:id="@+id/imgPic"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:visibility="gone" />
<ScrollView
android:id="@+id/scroll"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:visibility="gone">
<TextView
android:id="@+id/txtshow"
android:layout_width="wrap_content"
android:layout_height="wrap_content" />
</ScrollView>
<WebView
android:id="@+id/webView"
android:layout_width="match_parent"
android:layout_height="match_parent" />
</LinearLayout>