HttpURLConnection post请求


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;
}



评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值