使用HttpURLConnecation 进行通信
1、GET 请求:
new Thread() { public void run() { try { //1. 连接网络 创建URL对象 URL url = new URL("http://www.baidu.com"); //2.打开连接 并获得HttpURLConnection对象 HttpURLConnection huc = (HttpURLConnection) url.openConnection(); //3. 读取该对象资源的数据 huc.setDoInput(true);// 设置读取数据 huc.setRequestMethod("GET");//设置请求模式 GET huc.connect();//建立链接成功 //获得读取流 InputStream is = huc.getInputStream(); BufferedReader br = new BufferedReader(new InputStreamReader(is)); //4.获取读取到的字符数据 创建StringBuilder 对象 StringBuilder sb = new StringBuilder(); //5.读取数据 String line = ""; while((line=br.readLine())!=null) { sb.append(line+" "); //收集读取到的数据 } //获得Message对象 Message msg = Message.obtain(); msg.obj = sb; msg.what = 1; hd.sendMessage(msg); } catch (Exception e) { // TODO Auto-generated catch block e.printStackTrace(); } } }.start();
2、POST请求:
new Thread() { public void run() { try { // 1.获取URL对象 URL url = new URL("http://wwwtest.rupeng.cn:8888/QueryAvatarInfo.ashx"); // 2.获取HttpURLConnection 对象 HttpURLConnection huc = (HttpURLConnection) url.openConnection(); //3.设置 读入与写出 huc.setDoInput(true); huc.setDoOutput(true); //4.设置 请求模式 huc.setRequestMethod("POST"); //5.获取写入流 OutputStream os = huc.getOutputStream(); os.write(("action=GetAllNames").getBytes()); os.flush(); // 6.链接 huc.connect(); //7.读取返回数据 InputStream is = huc.getInputStream(); BufferedReader br = new BufferedReader(new InputStreamReader(is)); StringBuilder sb = new StringBuilder(); String line=""; while((line=br.readLine())!=null) { sb.append(line+" "); } Message msg = Message.obtain(); msg.obj = sb; msg.what = 1; // 发送数据 hd.sendMessage(msg); // 关闭资源 is.close(); br.close(); os.close(); } catch (Exception e) { // TODO Auto-generated catch block e.printStackTrace(); } }; }.start();
使用HttpClient 进行通信
GET
new Thread() { // 耗时操作 public void run() { //1、创建HttpClient对象 HttpClient hc = new DefaultHttpClient(); //2.设置请求模式 HttpGet hg = new HttpGet("http://www.baidu.com/"); try { //3.客户端执行 GET请求 获得应答对象 HttpResponse hr = hc.execute(hg); //4.通过应答对象获得 实体数据对象 HttpEntity he = hr.getEntity(); //5.通过EntityUtils工具类解析数据 String data = EntityUtils.toString(he,"UTF-8"); // 通过Handler发送数据 Message msg = Message.obtain(); msg.obj = data; msg.what = 1; hd.sendMessage(msg); } catch (ClientProtocolException e) { // TODO Auto-generated catch block e.printStackTrace(); } catch (Exception e) { // TODO Auto-generated catch block e.printStackTrace(); } } }.start();