为了方便我们与服务器的通信,我们需要实现一个网络通信基类。
实现代码如下:
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 通信地址
* @param method 通信方法 get post
* @param successCallback 通知调用者 成功
* @param failCallback 通知调用者 失败
* @param kvs 通信可变字符串参数
*/
public NetConnection(final String url,final HttpMethod method,final SuccessCallback successCallback,final FailCallback failCallback,final String ...kvs){
//网络链接会阻塞主线程,需要异步任务执行网络链接
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方式通信
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;
}
//通知调用者
@Override
protected void onPostExecute(String result) {
super.onPostExecute(result);
if(result != null){
if(successCallback != null){
successCallback.onSuccess(result);
}
}else{
if(failCallback != null){
failCallback.onFaid();
}
}
}
}.execute();
}
public static interface SuccessCallback{
void onSuccess(String result);
}
public static interface FailCallback{
void onFaid();
}
}
原文地址:http://blog.csdn.net/u013595878/article/details/43865597