Android与服务器通信
16lz
2021-01-23
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(); } }}
更多相关文章
- Android中NDK的使用方法
- Android的window类的常用方法
- Android 拨打webView 里面的电话号码的方法
- android 在线视频播放器实现方法
- Android下各文件方法获取的路径
- android intent的常用方法
- This Android SDK requires Android Developer Toolkit version
- Android Studio Start Failed解决方法