Http通信(HttpClient)
HttpURLConnection是java.net.*包提供的类,但java JDK 库本身功能还不够丰富和灵活;
Apache HttpClient是一个开源项目,功能更加完善,弥补了java.net.*灵活性不足的缺点。
使用HttpClient接口要加入httpclient-4.3.1.jar相关的jar包
private void getHttpClientConnection(String url){
final String getUrl = url;
new Thread(new Runnable() {//新建一个子线程
String getUrl2 = getUrl;
@Override
public void run() {
HttpClient hc = new DefaultHttpClient();//1.创建一个HttpClient,(DefaultHttpClient表示默认属性)
HttpGet hg = new HttpGet(getUrl2);//2.HttpGet实例,通过GET方法
InputStream in = null;
StringBuffer sb = null;
try{
HttpResponse hr = hc.execute(hg);//3.HttpResponse Http响应,HttpClient执行HttpGet方法
//连接成功
if ((hr.getStatusLine().getStatusCode()) == 200){//4.得到响应码,如果==200,连接成功
in = hr.getEntity().getContent();//5.获取返回的数据 InPutStream流获取响应得到的内容
BufferedReader br = new BufferedReader(new InputStreamReader(in));//BufferedReader读取数据流
char[] buf = new char[1024];
int longth = 0;
sb = new StringBuffer();
while((longth = br.read(buf)) != -1){//读取BufferedReader,放入StringBuffer
sb.append(buf,0,longth);
}
}
}catch(IOException e){
e.printStackTrace();
}finally{
if (in != null){
try {
in.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
Message message = new Message();//新建Message
message.what = CHANGE_TEXT;
message.obj = sb.toString();//Message.obj得到StringBuffer的内容
handler.sendMessage(message);//sendMessage
}
}).start();
}
-----------------------------------------
类中建一个Handler接收message
private static final int CHANGE_TEXT = 1;
private Handler handler = new Handler(){
@Override
public void handleMessage(Message msg) {
super.handleMessage(msg);
if (msg.what == CHANGE_TEXT){
textView.setText(msg.obj.toString());
}
}
};