HttpURLConnection请求工具类

 HttpUtil网络请求工具类:

import java.io.BufferedReader;
import java.io.DataOutputStream;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.OutputStream;
import java.net.HttpURLConnection;
import java.net.URL;
import org.json.JSONObject;
import android.util.Log;

public class HttpUtil {

	public static String getJsonData(JSONObject jsonParam, String urls) {
		StringBuffer sb = new StringBuffer();
		try {
			// 创建url资源  
			URL url = new URL(urls);
			// 建立http连接  
			HttpURLConnection conn = (HttpURLConnection) url.openConnection();
			// 设置允许输出
			conn.setDoOutput(true);
			// 设置允许输入  
			conn.setDoInput(true);
			// 设置不用缓存
			conn.setUseCaches(false);
			// 设置传递方式  
			conn.setRequestMethod("POST");
			// 设置维持长连接  
			conn.setRequestProperty("Connection", "Keep-Alive");
			// 设置文件字符集:
			conn.setRequestProperty("Charset", "UTF-8");
			// 转换为字节数组
			byte[] data = (jsonParam.toString()).getBytes();
			// 设置文件长度  
			conn.setRequestProperty("Content-Length", String.valueOf(data.length));
			// 设置文件类型:  
			conn.setRequestProperty("Content-Type", "application/json; charset=UTF-8");
			conn.setConnectTimeout(10000);

			conn.setRequestProperty("accept", "application/json");
			// 开始连接请求
			conn.connect();
			OutputStream out = new DataOutputStream(conn.getOutputStream());
			// 写入请求的字符串
			out.write((jsonParam.toString()).getBytes());
			out.flush();
			out.close();
			// 请求返回的状态
			if (HttpURLConnection.HTTP_OK == 200) {
				Log.e("longjing", "请求成功。。。");
				InputStream in1 = conn.getInputStream();
				try {
					String readLine = new String();
					BufferedReader responseReader = new BufferedReader(new InputStreamReader(in1, "UTF-8"));
					while ((readLine = responseReader.readLine()) != null) {
						sb.append(readLine).append("\n");
					}
					responseReader.close();
				} catch (Exception e1) {
					e1.printStackTrace();
				}
			} else {
				Log.e("longjing","请求失败。。。");
			}
		} catch (Exception e) {
			e.printStackTrace();
		}
		return sb.toString();
	}
}

网络请求:

new Thread(new Runnable(){
				@Override
				public void run() {
					try{
							JSONObject jsonParam = new JSONObject();
							jsonParam.put("eqpt_id",app.getCookie("eqpt_id"));
							String result = HttpUtil.getJsonData(jsonParam, Constant.IP+Constant.Get_Video_Url);//请求
					        if(result !=null && !"".equals(result.trim())){
							    Gson gs = new Gson();
							    GetVideoUrlBean mBean = gs.fromJson(result, GetVideoUrlBean.class);//把JSON字符串转为对象
                            }
					}catch(Exception e){
						e.printStackTrace();
					}
				}
			}).start();

 

  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值