WebView使用方法:
1、设置布局,在activity_main.xml中添加<webView>
<LinearLayout...... <webView android:id="@+id/web_view" android:layout_width="match_parent" android:layout_height="match_parent" </LinearLayout>
2、修改MainActivity中代码
Pubilc class MainActivity extends AppCompatActivity{ @Override protected void onCreate(Bundle saveInstanceState){ super.onCreate(saveInstanceState); setContentView(R.layout.activity_main); WebView webView = (WebView)findViewById(R.id.web_view); webView.getSettings().setJavaScriptEnabled(true); //支持JS webView.setWebViewClent(new WebViewClient()); //当前webView中显示网页 webView.loadUrl("http://www.baidu.com"); } }
3、访问网路需要声明权限:<use-permission android:name="android.permission.INTERNET" />
HTTP协议:
使用HttpURLConnection
1、获取HttpURLConnection实例
URL url = new URL("http://www.baidu.com");
HttpURLConnection connection = (HttpURLConnection) url.openConnection();
2、设置HTTP请求数据方法get/post
connection:setRequestMethod("GET"); //设置请求方法为GET
3、设置一些消息头
connection.setConnectTimeout(8000);
connection.setReadTimeout(8000);
4、获取从服务器返回的输入流
InputStream in = connection.getInputStream();
5、关闭HTTP
connection.disconnect();
POST方法向服务器提交数据:(键值对)
connection.setRequestMethod("POST");
DataOutputStream out = new DataOutputStream(connection.getOutputStream());
out.writeBytes("username = admin&password=123456");