MainActivity.java代码:
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import java.io.IOException;
import java.io.InputStream;
import java.net.HttpURLConnection;
import java.net.URL;
import java.net.URLConnection;
public class MainActivity extends AppCompatActivity {
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
}
public void accessNet(View view) {
new Thread(){
@Override
public void run() {
try {
// URL url = new URL("http://www.lnfvc.edu.cn/newweb/index.asp");
// URL url = new URL("https://www.baidu.com");
URL url = new URL("https://www.jianshu.com/p/cbbe59893263"); //进入网站
HttpURLConnection connection = (HttpURLConnection) url.openConnection(); //发送HTTP请求
connection.setRequestMethod("GET"); //GET表示从服务器哪里获取数据 POST 表示提交数据给服务器
connection.connect();
InputStream inputStream=connection.getInputStream();
int length=connection.getContentLength();
byte[] buf=new byte[9000];
int len=0;
while ((len=inputStream.read(buf))!=-1){
Log.i("len:",len+"......\r\n");
Log.i("html",new String(buf,0,len,"UTF-8")+"\n");
}
inputStream.close();
connection.disconnect();
} catch (IOException e) {
e.printStackTrace();
} finally {
}
}
}.start();
}
}
AndroidManifest.xml : 获取权限
uses-permission android:name="android.permission.INTERNET"></uses-permission>
activity_main
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
tools:context="com.lnjr.httpdemo.MainActivity"
android:orientation="horizontal">
<button 用于发送HTTP请求>
<Button
android:id="@+id/accessNet"
android:onClick="accessNet"
android:layout_width="match_parent"
android:layout_height="wrap_content" />
</LinearLayout>