我是靠谱客的博主 平淡鸡翅,这篇文章主要介绍使用HttpURLConnection访问URL地址,现在分享给大家,希望可以做个参考。

复制代码
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
<pre class="java" name="code">/* * 访问数据库 */ private Thread postThread = new Thread() { public void run() { String target = "您要访问的URL地址"; //要提交的目标地址 URL url; try { url = new URL(target); HttpURLConnection urlConn = (HttpURLConnection) url .openConnection(); // 创建一个HTTP连接 urlConn.setRequestMethod("POST"); // 指定使用POST请求方式 urlConn.setDoInput(true); // 向连接中写入数据 urlConn.setDoOutput(true); // 从连接中读取数据 urlConn.setUseCaches(false); // 禁止缓存 urlConn.setInstanceFollowRedirects(true); //自动执行HTTP重定向 urlConn.setRequestProperty("Content-Type", "application/x-www-form-urlencoded"); // 设置内容类型 DataOutputStream out = new DataOutputStream( urlConn.getOutputStream()); // 获取输出流 String param = "提交的参数=" + URLEncoder.encode(参数的值, "UTF-8") + "&提交的参数=" + URLEncoder.encode(参数的值, "UTF-8"); //连接要提交的数 out.writeBytes(param);//将要传递的数据写入数据输出流 out.flush(); //输出缓存 out.close(); //关闭数据输出流 if (urlConn.getResponseCode() == HttpURLConnection.HTTP_OK) { // 判断是否响应成功 InputStreamReader in = new InputStreamReader( urlConn.getInputStream(),"utf-8"); // 获得读取的内容,utf-8获取内容的编码 BufferedReader buffer = new BufferedReader(in); // 获取输入流对象 String inputLine = null; while ((inputLine = buffer.readLine()) != null) { Log.d("MainActivity", inputLine + "n"); try { JSONObject reader = new JSONObject(inputLine);//使用JSONObject解析 Log.i("MainActivity", "result_code:"+reader.getString("result_code")); } catch (JSONException e) { // TODO Auto-generated catch block e.printStackTrace(); Log.i("MainAcitvity", e.getMessage()); } // Message msg = new Message(); // msg.obj = inputLine; // handler.sendMessage(msg); } in.close(); //关闭字符输入流 } urlConn.disconnect(); //断开连接 } catch (MalformedURLException e) { e.printStackTrace(); } catch (IOException e) { e.printStackTrace(); } }; };

复制代码
1

在主线程中使用new Thread(postThread).start();启动子线程

这个方法可以直接使用,因为项目中服务器返回的是JSONObject所以用到了JSONObject解析,读者可以根据自己的需求酌情处理,另外JSONObject需要jar包

还有一点是需要注意的,就是在子线程中是不能使用Toast'的,如果使用程序就会死去

参数传递请使用全局变量和handler


最后

以上就是平淡鸡翅最近收集整理的关于使用HttpURLConnection访问URL地址的全部内容,更多相关使用HttpURLConnection访问URL地址内容请搜索靠谱客的其他文章。

本图文内容来源于网友提供,作为学习参考使用,或来自网络收集整理,版权属于原作者所有。
点赞(98)

评论列表共有 0 条评论

立即
投稿
返回
顶部