MainActivity.java:
package thonlon.example.cn.httpurlconnectionpro;
import android.os.Bundle;
import android.support.v7.app.AppCompatActivity;
import android.view.View;
import android.widget.Button;
import android.widget.TextView;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.net.HttpURLConnection;
import java.net.MalformedURLException;
import java.net.URL;
public class MainActivity extends AppCompatActivity {
private Button btn_req;
private TextView tv_res;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
initView();
}
private void initView() {
btn_req = (Button) findViewById(R.id.btn_req);
tv_res = (TextView) findViewById(R.id.tv_res);
}
public void onClick(View view) {
sendRequestHttpURLConnection();
}
public void sendRequestHttpURLConnection() {
new Thread(new Runnable() {
@Override
public void run() {
String urlStr = "https://www.baidu.com";
HttpURLConnection conn = null;
BufferedReader reader = null;
try {
URL url = new URL(urlStr);
conn = (HttpURLConnection) url.openConnection();
conn.setRequestMethod("GET");
conn.setConnectTimeout(8000);
conn.setReadTimeout(8000);
InputStream is = conn.getInputStream();
reader = new BufferedReader(new InputStreamReader(is));
StringBuilder response = new StringBuilder();
String line = null;
while ((line = reader.readLine()) != null) {
response.append(line);
}
showResponse(response.toString());
} catch (MalformedURLException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
} finally {
if (reader != null) {
try {
reader.close();
} catch (IOException e) {
e.printStackTrace();
}
}
if (conn != null) {
conn.disconnect();
}
}
}
}).start();
}
private void showResponse(final String response) {
runOnUiThread(new Runnable() {
@Override
public void run() {
tv_res.setText(response);
}
});
}
}