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.exe cute (get); // execute the Post method 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"); // construct the Post object HttpPost post = new HttpPost (url); post using encoding. setEntity (httpEntity); // set the Post object HttpClient client = new DefaultHttpClient (); HttpResponse response=client.exe cute (post); // execute the Post method return EntityUtils. toString (response. getEntity ();} catch (Exception e) {return "";}}}
2. Socket mode
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(); } }}