Android与服务器通信
1.Http方式
package com.myapp.util; import java.util.List; import org.apache.http.HttpEntity; import org.apache.http.HttpResponse; import org.apache.http.NameValuePair; import org.apache.http.client.HttpClient; import org.apache.http.client.entity.UrlEncodedFormEntity; import org.apache.http.client.methods.HttpGet; import org.apache.http.client.methods.HttpPost; import org.apache.http.impl.client.DefaultHttpClient; import org.apache.http.util.EntityUtils; public class MyUtil { public static String doGet(String url){ HttpGet get=new HttpGet(url); HttpClient client=new DefaultHttpClient(); String result=""; try { HttpResponse response=client.execute(get);//执行Post方法 result=EntityUtils.toString(response.getEntity()); }catch (Exception e) { return ""; } return result; } public String doPost(String url,List<NameValuePair> values){ try { HttpEntity httpEntity=new UrlEncodedFormEntity(values,"UTF-8");//使用编码构建Post实体 HttpPost post=new HttpPost(url); post.setEntity(httpEntity);//设置Post实体 HttpClient client=new DefaultHttpClient(); HttpResponse response=client.execute(post);//执行Post方法 return EntityUtils.toString(response.getEntity()); } catch (Exception e) { return ""; } } }
2.Socket方式
package com.bjdata.myapp.util; import java.io.*; import java.net.*; public class SocketClient { static Socket client; public SocketClient(String site, int port){ try{ client = new Socket(site,port); System.out.println("Client is created! site:"+site+" port:"+port); }catch (UnknownHostException e){ e.printStackTrace(); }catch (IOException e){ e.printStackTrace(); } } public String sendMsg(String msg){ try{ BufferedReader in = new BufferedReader(new InputStreamReader(client.getInputStream())); PrintWriter out = new PrintWriter(client.getOutputStream()); out.println(msg); out.flush(); return in.readLine(); }catch(IOException e){ e.printStackTrace(); } return ""; } public void closeSocket(){ try{ client.close(); }catch(IOException e){ e.printStackTrace(); } } }