1.http工作原理:客服端向服务器发送一条http请求,服务器收到请求后返回数据给客户端,客户端收到数据后进行解析。
1.1添加访问网络权限
<uses-permission android:name="android.permission.INTERNET"/>
1.2实例代码
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:gravity="center_horizontal"
android:orientation="vertical">
<Button
android:id="@+id/take_photo"
android:layout_width="match_parent"
android:layout_height="45dp"
android:text="拍照"/>
<ScrollView
android:layout_width="match_parent"
android:layout_height="match_parent">
<TextView
android:id="@+id/tv_content"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:textSize="12sp"
android:textColor="#000000"/>
</ScrollView>
</LinearLayout>
public class MainActivity extends Activity implements View.OnClickListener {
Button take_photo;
TextView tv_content;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
take_photo=findViewById(R.id.take_photo);
tv_content=findViewById(R.id.tv_content);
take_photo.setOnClickListener(this);
}
@Override
public void onClick(View view) {
sendRequestWithHttpURLConnection();
}
private void sendRequestWithHttpURLConnection() {
//开启新线程来发起网络请求
new Thread(new Runnable() {
@Override
public void run() {
HttpURLConnection connection=null;
BufferedReader reader=null;
try {
//1.创建URL对象
URL url=new URL("https://www.baidu.com");
//2.HttpURLConnection对象
connection= (HttpURLConnection) url.openConnection();
//3.设置请求方式
connection.setRequestMethod("GET");
//4.设置属性如连接超时、读取超时的毫秒数
connection.setConnectTimeout(8000);
connection.setReadTimeout(8000);
//5.获取服务器返回的输入输出流
InputStream in=connection.getInputStream();
//下面对获取到的输入流进行读取
reader=new BufferedReader(new InputStreamReader(in));
StringBuilder response=new StringBuilder();
String line;
while ((line=reader.readLine())!=null){
response.append(line);
}
showResponse(response.toString());
} catch (Exception e) {
e.printStackTrace();
}finally {
if (reader!=null){
try {
reader.close();
}catch (IOException e){
e.printStackTrace();
}
}
if (connection!=null){
//6.关闭http连接
connection.disconnect();
}
}
}
}).start();
}
private void showResponse(final String s) {
runOnUiThread(new Runnable() {
@Override
public void run() {
//在这里进行ui操作
tv_content.setText(s);
}
});
}
}
1.3如果是提交数据,只需将请求方式改为POST,并在获取输入流之前把要提交的数据写出即可。注:每条数据以键值对的形式存在数据
与数据之间用“&”符号隔开,比如向服务器提交用户名和密码:
connection.setRequestMethod("POST");
DataOutputStream out=new DataOutputStream(connection.getOutputStream());
out.writeBytes("username=admin&password=123456");