一、使用HttpURLConnection的步驟
1、獲取到HttpURLConnection的實例,並傳入目標的網絡地址,然後調用openConnection()方法
URL url = new URL("http://www.baidu.com");
HttpURLConnection connection = (HttpURLConnection)url.openConnection();
2、設置HTTP請求所使用的方法GET和POST
GET:從服務器那裏獲取數據
之後再調用getInputStream()方法獲取到服務器返回的輸入流
connection.setRequestMethod("GET");
InputStream in = connection.getInputStream();
POST:提交數據給服務器
每條數據都要以鍵值對的形式存在,數據與數據之間用“&”符號隔開
connection.setRequestMethod("POST");
DataOutputStream out = new DataOutputStream(connection.getOutputStream());
out.writeBytes("username=admin&password=123456");
3、調用disconnect()方法將HTTP連接關閉掉
connection.disconnect();
二、實例
需求:一個按鈕用於發送HTTP請求,一個文本框用於將服務器返回的數據顯示出來
1、效果圖
2、佈局文件
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout
xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical">
<Button
android:id="@+id/send_request"
android:layout_width="match_parent"
android:layout_height="80dp"
android:text="發送請求"
android:textSize="25dp"/>
<ScrollView
android:layout_width="match_parent"
android:layout_height="match_parent">
<TextView
android:id="@+id/response_text"
android:layout_width="match_parent"
android:layout_height="wrap_content" />
</ScrollView>
</LinearLayout>
3、MainActivity.java
public class MainActivity extends AppCompatActivity implements View.OnClickListener {
TextView responseText;
Button sendRequset;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
sendRequset = (Button) findViewById(R.id.send_request);
responseText = (TextView) findViewById(R.id.response_text);
sendRequset.setOnClickListener(this);
}
@Override
public void onClick(View view) {
if (view.getId() == R.id.send_request){
sendRequsetWithHttpURLConnection();
}
}
private void sendRequsetWithHttpURLConnection() {
//開啓線程來發起網絡請求
new Thread(new Runnable() {
@Override
public void run() {
HttpURLConnection connection = null;
BufferedReader reader = null;
try {
URL url = new URL("http://www.baidu.com");
connection = (HttpURLConnection) url.openConnection();
//提交數據給服務器的步驟
// connection.setRequestMethod("POST");
// DataOutputStream out = new DataOutputStream(connection.getOutputStream());
// out.writeBytes("username=admin&password=123456");
connection.setRequestMethod("GET");
//設置鏈接超時的毫秒數
connection.setConnectTimeout(8000);
//設置讀取超時的毫秒數
connection.setReadTimeout(8000);
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){
connection.disconnect();
}
}
}
}).start();
}
//結果傳入showResponse方法中
private void showResponse(final String s) {
runOnUiThread(new Runnable() {
@Override
public void run() {
//在這裏進行UI操作,將結果顯示到界面上
responseText.setText(s);
}
});
}
}
4、聲明網絡權限
<uses-permission android:name="android.permission.INTERNET"/>