声明:笔者参考《第一行代码》一书!
在Android中,发送Http网络请求的方式一般有2种,HttpURLConnection和HttpClient。
下面先使用前者,代码如下:
先来看一下布局文件:
<?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"
android:orientation="vertical"
tools:context="com.yu.httpurlconnection.MainActivity">
<Button
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:text="发送HTTP请求"
android:id="@+id/send"
android:layout_gravity="center_horizontal" />
<ScrollView
android:layout_width="match_parent"
android:layout_height="match_parent"
android:id="@+id/scrollView"
>
<TextView
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:id="@+id/textview"/>
</ScrollView>
</LinearLayout>
核心代码如下(HttpURLConnection):
public class MainActivity extends AppCompatActivity {
private Button mSend;
private TextView mTextView;
Handler handler = new Handler(){
@Override
public void handleMessage(Message msg) {
if(msg.what==1){
String text = (String) msg.obj;
mTextView.setText(text);
}
super.handleMessage(msg);
}
};
private HttpURLConnection connection;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
mTextView= (TextView) findViewById(R.id.textview);
mSend= (Button) findViewById(R.id.send);
mSend.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
sendHttp();
}
});
}
private void sendHttp() {
//请求网络比较耗时,所以放在子线程中
new Thread(new Runnable() {
@Override
public void run() {
try {
URL uri = new URL("https://www.baidu.com/");
connection = (HttpURLConnection) uri.openConnection();
connection.setRequestMethod("GET");
connection.setConnectTimeout(5000);
connection.setReadTimeout(5000);
InputStream inputStream = connection.getInputStream();
StringBuilder sb = new StringBuilder();
BufferedReader reader = new BufferedReader(new InputStreamReader(inputStream));
String line;
while((line=reader.readLine())!=null){
sb.append(line);
}
Message message = new Message();
message.obj = sb.toString();
message.what = 1;
handler.sendMessage(message);
} catch (Exception e) {
e.printStackTrace();
}finally {
if(connection!=null){
connection.disconnect();
}
}
}
}).start();
}
}
下面用HttpClient:
PS:HttpClient好像被谷歌弃用了,所以想要使用它的话,导入jar包
public class MainActivity extends AppCompatActivity {
private Button mSend;
private TextView mTextView;
Handler handler = new Handler(){
@Override
public void handleMessage(Message msg) {
if(msg.what==2){
String text = (String) msg.obj;
mTextView.setText(text);
}
super.handleMessage(msg);
}
};
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
mTextView= (TextView) findViewById(R.id.textview);
mSend= (Button) findViewById(R.id.send);
mSend.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
sendHttp();
}
});
}
private void sendHttp() {
new Thread(new Runnable() {
@Override
public void run() {
try {
HttpClient mHttpClient = new DefaultHttpClient();
HttpGet mHttpGet =new HttpGet("https://www.baidu.com/");
HttpResponse response = mHttpClient.execute(mHttpGet);
if(response.getStatusLine().getStatusCode()==200){
HttpEntity httpEntity = response.getEntity();
String result = EntityUtils.toString(httpEntity,"utf-8");
Message message = new Message();
message.obj = result;
message.what=2;
handler.sendMessage(message);
}
} catch (Exception e) {
e.printStackTrace();
}finally {
if(connection!=null){
connection.disconnect();
}
}
}
}).start();
}
}
运行效果: