HttpURLConnection 网络通信

import java.io.IOException;
import java.io.InputStream;
import java.io.PrintWriter;
import java.io.UnsupportedEncodingException;
import java.net.HttpURLConnection;
import java.net.URL;

public class Http {

	public static InputStream Get(String httpUrl) {
		InputStream readStream = null;

		String check = encrypt(httpUrl);
		try {
			URL url = new URL(httpUrl);
			HttpURLConnection conn = (HttpURLConnection) url.openConnection();
			conn.setUseCaches(false);
			conn.setRequestMethod("GET");
			conn.setRequestProperty("Check", check);
			conn.setConnectTimeout(20000);
			conn.setReadTimeout(50000);
			if (conn.getResponseCode() == 200) {
				readStream = conn.getInputStream();
			}
		} catch (Exception e) {
			return null;
		}
		return readStream;
	}
	
	public static InputStream Post(String httpUrl, String data) {
		PrintWriter out = null;
		InputStream readStream = null;
		String output = "";
		try {
			output = new String(data.getBytes(), "utf-8");
		} catch (UnsupportedEncodingException e1) {
			e1.printStackTrace();
		}
		try {
			URL postUrl = new URL(httpUrl);
			HttpURLConnection conn = (HttpURLConnection) postUrl.openConnection();
			conn.setConnectTimeout(5000);
			conn.setDoOutput(true);// 允许输出
			conn.setDoInput(true);
			conn.setUseCaches(false);// 不使用缓存
			conn.setRequestMethod("POST");
			conn.setRequestProperty("accept", "*/*");
			conn.setRequestProperty("Connection", "Keep-Alive");// 维持长连接
			conn.setRequestProperty("Charset", "UTF-8");
			conn.setRequestProperty("Content-Type", "application/x-www-form-urlencoded; charset=UTF-8");
			out = new PrintWriter(conn.getOutputStream());
			out.print(output);
			out.flush();
			out.close();
			if (conn.getResponseCode() != 200) {
				throw new Exception("请求url失败");
			}
			readStream = conn.getInputStream();
			
			return readStream;
		} catch (Exception e) {
			e.printStackTrace();
			return readStream;
		} finally {
			if (out != null) {
				out.close();
			}
			if (readStream != null) {
				try {
					readStream.close();
				} catch (IOException e) {
					return null;
				}
			}
		}
	}
	
	private static String encrypt(String httpurl){
		String result = "";

		return result;
	}
}

 

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值