HttpURLConnection 用法
Android的网络通信的方式有两种:
- Socket
- HTTP
而其中,HTTP又包括两种编程方式:
- HttpURLConnection
- HttpClient
这篇文章介绍的就是,HttpURLConnection
首先,当然是创建HttpURLConnection的对象
URL url = new URL("www.baidu.com");
HttpURLConnection connection=(HttpURLConnection)url.openConnection();
第二步是设置,其中最重要的就是 GET or POST?(GET是从服务器读取数据,POST是提交数据给服务器)
connection.setRequestMethod("GET");
connection.setConnectTimeout(8000);//连接超时
connection.setReadTimeout(8000);//读取超时
接着,就可以从connection中获取数据了
InputStream in = connection.getInputStream();
最后需要关闭连接
connection.disconnect();
例子
要访问网络,所以需要在清单文件里添加权限:
<uses-permission android:name="android.permission.INTERNET"/>
MainActivity.java
public class MainActivity extends Activity implements OnClickListener {
private Button sendRequest;
private TextView responseText;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
sendRequest = (Button) findViewById(R.id.send_request);
responseText = (TextView) findViewById(R.id.response);
sendRequest.setOnClickListener(this);
}
@Override
public void onClick(View v) {
// TODO Auto-generated method stub
if (v.getId() == R.id.send_request) {
sendRequestWithHttpURLConnection();
}
}
private void sendRequestWithHttpURLConnection() {
new Thread(new Runnable() {
@Override
public void run() {
// TODO Auto-generated method stub
HttpURLConnection connection = null;
try {
URL url = new URL("www.baidu.com");
connection = (HttpURLConnection) url.openConnection();
connection.setConnectTimeout(8000);
connection.setReadTimeout(8000);
connection.setRequestMethod("GET");
String line = null;
StringBuilder response = new StringBuilder();
InputStream in = connection.getInputStream();
BufferedReader reader = new BufferedReader(
new InputStreamReader(in));
while ((line = reader.readLine()) != null) {
response.append(line);
Log.e("MainActivity", line);
}
responseText.setText(response.toString());
} catch (Exception e) {
e.printStackTrace();
} finally {
if (connection != null)
connection.disconnect();
}
}
}).start();
}
}
上面代码的逻辑很简单,就是:点击“发送”按钮,从百度首页获取数据,并显示在文本框里。
但这里有两个问题需要注意:
- 写网址,也就是URL时,需要加上协议名,也就是"http://"
- 上面的代码如果真的运行,文本框里是不会显示任何内容的,因为子线程中无法对 UI 进行操作
第一个问题容易解决,加上http://就行了。
而第二个问题,解决的办法是:创建一个Message对象,使用Handler把它发送出去,在Handler的方法里来处理这条Message。
修改后的代码
public class MainActivity extends Activity implements OnClickListener {
private Button sendRequest;
private TextView responseText;
public static final int SHOW_RESPONSE = 0;
private Handler handler = new Handler(){
public void handleMessage(Message msg){
switch (msg.what) {
case SHOW_RESPONSE:
String response = (String)msg.obj;
responseText.setText(response);
break;
default:
break;
}
}
};
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
sendRequest = (Button) findViewById(R.id.send_request);
responseText = (TextView) findViewById(R.id.response);
sendRequest.setOnClickListener(this);
}
@Override
public void onClick(View v) {
// TODO Auto-generated method stub
if (v.getId() == R.id.send_request) {
sendRequestWithHttpURLConnection();
}
}
private void sendRequestWithHttpURLConnection() {
new Thread(new Runnable() {
@Override
public void run() {
// TODO Auto-generated method stub
HttpURLConnection connection = null;
try {
URL url = new URL("http://www.baidu.com");
connection = (HttpURLConnection) url.openConnection();
connection.setConnectTimeout(8000);
connection.setReadTimeout(8000);
connection.setRequestMethod("GET");
String line = null;
StringBuilder response = new StringBuilder();
InputStream in = connection.getInputStream();
BufferedReader reader = new BufferedReader(
new InputStreamReader(in));
while ((line = reader.readLine()) != null) {
response.append(line);
Log.e("MainActivity", line);
}
Message message = new Message();
message.what = SHOW_RESPONSE;
message.obj = response.toString();
handler.sendMessage(message);
} catch (Exception e) {
e.printStackTrace();
} finally {
if (connection != null)
connection.disconnect();
}
}
}).start();
}
}
如果在本机上开了Tomcat服务器,那么URL里的内容就可以是http://192.168.0.100:8080
这样,点击按钮后,就能在文本框里显示本机里的这个URL的内容了。
莫问前程