Implementation of the Android network communication base class and android Network Communication
To facilitate our communication with the server, we need to implement a network communication base class.
The implementation code is as follows:
Import java. io. BufferedReader;
Import java. io. BufferedWriter;
Import java. io. IOException;
Import java. io. InputStreamReader;
Import java. io. OutputStreamWriter;
Import java.net. MalformedURLException;
Import java.net. URL;
Import java.net. URLConnection;
Import com. jikexueyuan. secret. Config;
Import android. OS. AsyncTask;
Public class NetConnection {
/**
*
* @ Param url: communication address
* @ Param method: communication method get post
* @ Param successCallback: the caller is notified of successful calls.
* @ Param failCallback: The caller fails to be notified.
* @ Param kvs variable communication string parameter
*/
Public NetConnection (final String url, final HttpMethod method, final SuccessCallback successCallback, final FailCallback failCallback, final String... kvs ){
// The network link will block the main thread and the asynchronous task needs to execute the network link
New AsyncTask <Void, Void, String> (){
@ Override
Protected String doInBackground (Void... arg0 ){
StringBuffer paramsStr = new StringBuffer ();
For (int I = 0; I <kvs. length; I + = 2 ){
ParamsStr. append (kvs [I]). append ("="). append (kvs [I + 1]). append ("&");
}
Try {
URLConnection uc;
Switch (method ){
Case POST: // post Communication
Uc = new URL (url). openConnection ();
Uc. setDoOutput (true );
BufferedWriter bw = new BufferedWriter (new OutputStreamWriter (uc. getOutputStream (), Config. CHARSET ));
Bw. write (paramsStr. toString ());
Bw. flush ();
Break;
Default: // get
Uc = new URL (url + "? "+ ParamsStr. toString (). openConnection ();
Break;
}
System. out. println ("Request url:" + uc. getURL ());
System. out. println ("Request data:" + paramsStr );
BufferedReader br = new BufferedReader (new InputStreamReader (uc. getInputStream (), Config. CHARSET ));
String line = null;
StringBuffer result = new StringBuffer ();
While (line = br. readLine ())! = Null ){
Result. append (line );
}
System. out. println ("Result" + result );
Return result. toString ();
} Catch (MalformedURLException e ){
// TODO Auto-generated catch block
E. printStackTrace ();
} Catch (IOException e ){
// TODO Auto-generated catch block
E. printStackTrace ();
}
Return null;
}
// Notify the caller
@ Override
Protected void onPostExecute (String result ){
Super. onPostExecute (result );
If (result! = Null ){
If (successCallback! = Null ){
SuccessCallback. onSuccess (result );
}
} Else {
If (failCallback! = Null ){
FailCallback. onFaid ();
}
}
}
Cmd.exe cute ();
}
Public static interface SuccessCallback {
Void onSuccess (String result );
}
Public static interface FailCallback {
Void onFaid ();
}
}