java利用HttpURLConnection传数据

String urlStr = "http://localhost:8080/user/sendMessage";
2. String result = "";
3. URL url = null;
4. HttpURLConnection conn = null;
5. OutputStream os = null;
6. BufferedReader in = null;
7. try {
8. url = new URL(urlStr);
9. conn= (HttpURLConnection) url.openConnection();
10. conn.setDoInput(true);
11. conn.setDoOutput(true);
12. conn.setUseCaches(false);
13. //设置连接超时
14. conn.setConnectTimeout(50000);
15. //设置读取超时
16. conn.setReadTimeout(50000);
17. conn.setRequestMethod("POST");
18. conn.setRequestProperty("Content-Type", "application/x-www-form-urlencoded");
19. conn.connect();
20. //参数
21. String param = "name=xxx&token=xxx";
22. //写入数据
23. os = conn.getOutputStream();
24. os.write(param.getBytes("UTF-8"));
25. os.flush();
26. os.close();
27. //读取返回数据
28. if (conn.getResponseCode() == HttpURLConnection.HTTP_OK) {
29. in = new BufferedReader(new InputStreamReader(conn.getInputStream(), "utf-8"));
30. String inputLine;
31. while ((inputLine = in.readLine()) != null) {
32. result += inputLine;
33. }
34. in.close();
35. }
36. } catch (Exception e) {
37. e.printStackTrace();
38. } finally {
39. if (conn != null) conn.disconnect();
40. }


2、get请求


Java代码 复制代码 收藏代码
1.String urlStr = "http://localhost:8080/user/sendMessage?&name=xxx&token=xxx";
2. BufferedReader reader = null;
3. String line = null;
4. StringBuffer result = new StringBuffer();
5. URL url;
6. try {
7. url = new URL(urlStr);
8. HttpURLConnection con = (HttpURLConnection) url.openConnection();
9. con.setUseCaches(false);
10. reader = new BufferedReader(new InputStreamReader(con.getInputStream(), "UTF-8"));
11. while (null != (line = reader.readLine())) {
12. result.append(line);
13. }
14. if (reader != null) {
15. reader.close();
16. }
17. } catch (Exception e) {
18. e.printStackTrace();
19. }
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值