import android.os.Handler;
import android.os.Message;
import com.qf.mystock.constant.RequestResult;
import org.json.JSONObject;
import java.io.InputStream;
import java.io.OutputStream;
import java.net.HttpURLConnection;
import java.net.URL;
/**
* Created by QF on 2015/8/16.
*/
public class ServicePost extends Thread {
private String strURL;
private JSONObject jsonObject;
private Handler handler;
public ServicePost(String strURL, JSONObject jsonObject, Handler handler) {
this.strURL = strURL;
this.jsonObject = jsonObject;
this.handler = handler;
}
@Override
public void run() {
super.run();
try {
String path =strURL;
String encoding="UTF-8";
String params=jsonObject.toString();
byte[] data = params.getBytes(encoding);
URL url =new URL(path);
HttpURLConnection connection = (HttpURLConnection) url.openConnection();
connection.setRequestMethod("POST");
connection.setReadTimeout(5000);
connection.setConnectTimeout(5000);
connection.setRequestProperty("Connection", "keep-alive");
connection.setRequestProperty("Content-Type", "application/x-www-form-urlencoded");
connection.setRequestProperty("Content-Length", String.valueOf(data.length));
connection.setDoOutput(true);
connection.setDoInput(true);
OutputStream out = connection.getOutputStream();
out.write(data);
out.flush();
out.close();
if(connection.getResponseCode()==200){
InputStream inStream = connection.getInputStream();
StringBuffer sb = new StringBuffer();
byte[] b = new byte[1024];
for (int n; (n = inStream.read(b)) != -1;) {
sb.append(new String(b, 0, n));
}
String result=sb.toString();
System.out.println("result======="+result);
Message message = new Message();
message.what = RequestResult.SUCCESS;
message.obj = result;
handler.sendMessage(message);
}else {
handler.sendEmptyMessage(RequestResult.FAIL);
}
} catch (Exception e) {
handler.sendEmptyMessage(RequestResult.ERROR);
}
}
}
public class RequestResult
{
/**
* 成功
*/
public static final int SUCCESS = 1;
/**
* 失败
*/
public static final int FAIL = 0;
/**
* 异常
*/
public static final int ERROR = 2;
}