HtttpURLConnection 发送HTTP请求
public class MainActivity extends AppCompatActivity implements View.OnClickListener {
TextView responseText;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
Button sendRequest = (Button)findViewById(R.id.btn);
responseText = (TextView)findViewById(R.id.response_text);
sendRequest.setOnClickListener(this);
}
@Override
public void onClick(View v) {
if(v.getId() == R.id.btn){
sendRequestWithHttpURLConnection();
}
}
private void sendRequestWithHttpURLConnection() {
new Thread(new Runnable() {
@Override
public void run() {
HttpURLConnection connection = null;
BufferedReader reader= null;
try{
URL url = new URL("https://www.baidu.com/");
connection = (HttpURLConnection)url.openConnection();
connection.setRequestMethod("GET");
connection.setConnectTimeout(8000);
connection.setReadTimeout(100);
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();
}
private void showResponse( final String s) {
runOnUiThread(new Runnable() {
@Override
public void run() {
responseText.setText(s);
}
});
}
}