直接上干货,实例代码:
import android.annotation.SuppressLint;
import android.app.Activity;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.view.KeyEvent;
import android.view.View;
import android.widget.TextView;
import java.io.BufferedInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.net.HttpURLConnection;
import java.net.URL;
import java.util.Scanner;
public class MainActivity extends Activity {
private static final String TAG = "MainActivity";
private static final int SHOW_RESPONSE = 0;
@SuppressLint("HandlerLeak")
private Handler handler = new Handler() {
@Override
public void handleMessage(Message msg) {
switch (msg.what) {
case SHOW_RESPONSE:
String response = (String) msg.obj;
TextView textView = MainActivity.this.findViewById(R.id.response_text);
if (null != textView) {
textView.setText(response);
}
}
super.handleMessage(msg);
}
};
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
}
@Override
public boolean onKeyUp(int keyCode, KeyEvent event) {
if (keyCode == KeyEvent.KEYCODE_BACK) {
moveTaskToBack(true);
}
return super.onKeyUp(keyCode, event);
}
@Override
protected void onResume() {
super.onResume();
}
@Override
protected void onDestroy() {
super.onDestroy();
}
private String readInStream(InputStream in) {
Scanner scanner = new Scanner(in).useDelimiter("\\A");
return scanner.hasNext() ? scanner.next() : "";
}
public void sendRequestWithHttpURLConnection(View view) {
new Thread(new Runnable() {
@Override
public void run() {
HttpURLConnection urlConnection = null;
try {
URL url = new URL("https://www.baidu.com/");
urlConnection = (HttpURLConnection)url.openConnection();
Message message = new Message();
message.what = SHOW_RESPONSE;
message.obj =
readInStream(new BufferedInputStream(urlConnection.getInputStream()));
handler.sendMessage(message);
} catch (IOException e) {
e.printStackTrace();
} finally {
urlConnection.disconnect();
}
}
}).start();
}
}
布局文件的代码如下:
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
tools:context=".MainActivity"
android:orientation="vertical"
>
<Button
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:text="@string/send_request_with_http_url_connection"
android:onClick="sendRequestWithHttpURLConnection"
/>
<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"
android:text="@string/input_some_text_here"
/>
</ScrollView>
</LinearLayout>
本文参考自 《Android 第一行代码》
网友评论