关闭

Java利用HttpURLConnection发送请求

标签: HttpURLConnectionhttpurlpostget
243人阅读 评论(0) 收藏 举报
分类:

1、post请求

String urlStr = "http://localhost:8080/user/sendMessage";
	String result = "";
	URL url = null;
	HttpURLConnection conn = null;
	OutputStream os = null;
	BufferedReader in = null;
	try {
		url = new URL(urlStr);
		conn= (HttpURLConnection) url.openConnection();
		conn.setDoInput(true);
		conn.setDoOutput(true);
		conn.setUseCaches(false);
		//设置连接超时
		conn.setConnectTimeout(50000);
		//设置读取超时
		conn.setReadTimeout(50000);	
		conn.setRequestMethod("POST");
		conn.setRequestProperty("Content-Type", "application/x-www-form-urlencoded");
		conn.connect();
		//参数
		String param = "name=xxx&token=xxx";
		//写入数据
		os = conn.getOutputStream();
		os.write(param.getBytes("UTF-8"));
		os.flush();
		os.close();
		//读取返回数据
		if (conn.getResponseCode() == HttpURLConnection.HTTP_OK) {
			in = new BufferedReader(new InputStreamReader(conn.getInputStream(), "utf-8"));
			String inputLine;
			while ((inputLine = in.readLine()) != null) {
				result += inputLine;
			}
			in.close();
		}
	} catch (Exception e) {
		e.printStackTrace();
	} finally {
		if (conn != null) conn.disconnect();
	}
 2、get请求

String urlStr = "http://localhost:8080/user/sendMessage?&name=xxx&token=xxx";
	BufferedReader reader = null;
	String line = null;
	StringBuffer result = new StringBuffer();
	URL url;
	try {
		url = new URL(urlStr);
		HttpURLConnection con = (HttpURLConnection) url.openConnection();
		con.setUseCaches(false);
		reader = new BufferedReader(new InputStreamReader(con.getInputStream(), "UTF-8"));
		while (null != (line = reader.readLine())) {
			result.append(line);
		}
		if (reader != null) {
			reader.close();
		}
	} catch (Exception e) {
		e.printStackTrace();
	}



0
0

查看评论
* 以上用户言论只代表其个人观点,不代表CSDN网站的观点或立场
    个人资料
    • 访问:149652次
    • 积分:1362
    • 等级:
    • 排名:千里之外
    • 原创:35篇
    • 转载:2篇
    • 译文:0篇
    • 评论:12条
    文章分类
    最新评论