1.回调接口
/**
* 回调接口
*/
public interface InfoRequestCallback {
public void onSuccess(String result);
public void onFail(String result);
}
2.post请求
import android.content.Context;
import android.os.Handler;
import android.os.Message;
import com.lidroid.xutils.HttpUtils;
import java.io.ByteArrayOutputStream;
import java.io.InputStream;
import java.io.OutputStream;
import java.net.HttpURLConnection;
import java.net.URL;
/**
*基本POST请求
*/
public class InfoRequest {
static HttpUtils httpUtils;
public InfoRequest(Context context) {
httpUtils = new HttpUtils();
}
public static void doPost(final String uri,final String jsonparms,final InfoRequestCallback callback) {
final Handler hanler =new Handler(){
@Override
public void handleMessage(Message msg) {
// TODO Auto-generated method stub
int i=msg.arg1;
if(i==1){
callback.onSuccess((String)msg.obj);
}else{
callback.onFail((String)msg.obj);
}
}
};
Thread threaddopost = new Thread() {
@Override
public void run() {
try {
URL url = new URL(uri);
HttpURLConnection urlConnection = (HttpURLConnection) url.openConnection();
urlConnection.setRequestMethod("POST");
// urlConnection.setRequestProperty("Content-Type", "application/json");
urlConnection.setReadTimeout(5000);
urlConnection.setConnectTimeout(5000);
urlConnection.setRequestProperty("Content-type", "application/json; charset=utf-8");
urlConnection.setRequestProperty("Accept", "application/json");
urlConnection.setDoOutput(true); // 发送POST请求必须设置允许输出
urlConnection.setDoInput(true); // 发送POST请求必须设置允许输入
OutputStream os = urlConnection.getOutputStream();
os.write(jsonparms.getBytes());
os.flush();
String result="";
if (urlConnection.getResponseCode() == 200) {
String s= urlConnection.getResponseMessage();
// 获取响应的输入流对象
InputStream is = urlConnection.getInputStream();
// 创建字节输出流对象
ByteArrayOutputStream baos = new ByteArrayOutputStream();
// 定义读取的长度
int len = 0;
// 定义缓冲区
byte buffer[] = new byte[1024];
// 按照缓冲区的大小,循环读取
while ((len = is.read(buffer)) != -1) {
// 根据读取的长度写入到os对象中
baos.write(buffer, 0, len);
}
is.close();
baos.close();
result = new String(baos.toByteArray());
} else {
//System.out.println("链接失败.........");
result = "链接失败,返回码:"+urlConnection.getResponseCode();
}
Message ms=Message.obtain();
ms.arg1=1;
ms.obj=result;
hanler.sendMessage(ms);
} catch (Exception e) {
Message ms=Message.obtain();
ms.arg1=0;
ms.obj=e.getMessage();
hanler.sendMessage(ms);
e.printStackTrace();
}
}
};
threaddopost.start();
}
}