1.使用java.net.URL类访问网络数据
扫描二维码
随时随地手机看文章
和网络打交道总是难免的,所以很有必要学一下怎么操作和网络交互。
我们通过URL类或者HttpClient类,都可以对网络访问,至于这两个类的区别,HttpClient类底层还是使用了Url类,对其封装了一下。
第一步:建立一个服务器端,其中get方法返回"you had receied the message from http://192.168.1.132:8088/WebServer/student.do”;post方法返回输入的name。
package org.servlet; import java.io.IOException; import java.io.PrintWriter; import javax.servlet.ServletException; import javax.servlet.http.HttpServlet; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; public class StudentAction extends HttpServlet { private static final long serialVersionUID = 1L; public StudentAction() { } protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { PrintWriter out = response.getWriter(); out.write("you had receied the message from http://192.168.1.132:8088/WebServer/student.do"); } protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { request.setCharacterEncoding("UTF-8"); String name = request.getParameter("name"); PrintWriter out = response.getWriter(); out.write(name); } }
第二步:新建android projiect,新建一个java类,这里首先使用URL类,代码如下:
其中添加一个get方法:
package org.example.httpclient; import java.io.ByteArrayOutputStream; import java.io.InputStream; import java.net.HttpURLConnection; import java.net.URL; public class MHttpClient { public void get() throws Exception { // 实例化一个URL对象 URL url = new URL("http://192.168.1.132:8088/WebServer/student.do"); // 打开连接 HttpURLConnection conn = (HttpURLConnection) url.openConnection(); // 设置访问超时时间 conn.setConnectTimeout(5 * 1000); // 设置请求参数 conn.setRequestMethod("GET"); // 得到输入流 InputStream in = conn.getInputStream(); // 从输入流中读取内容放到内存中 ByteArrayOutputStream out = new ByteArrayOutputStream(); byte[] buffer = new byte[1024]; int len = 0; while ((len = in.read(buffer)) != -1) { out.write(buffer, 0, len); } System.out.println(new String(out.toByteArray())); out.close(); in.close(); } }
我们使用单元测试,在manifest.xml里添加
别忘了加入internet访问权限,否则就会报java.net.UnknownHostException的错误。
接下来新建一个MHttpclientTestCase类,需要继承AndroidTestCase类
添加一个测试方法:
public void testGet() throws Exception { MHttpClient url = new MHttpClient(); url.get(); }
然后在该文件右键->run as->android JUnit Test
可以在logcat中看到返回的信息“you had receied the message from http://192.168.1.132:8088/WebServer/student.do”。
如果要在请求中带参数的话,直接把参数附加到请求路径的后面就可以了,比如:http://www.baidu.com/s?wd=1&rsv_bp=0&rsv_spt=3&inputT=576
接下来,我们使用post请求。再MHttpClient类中建一个方法:
public void post() throws Exception { String postData = "name=11"; // 实例化一个URL对象 URL url = new URL("http://192.168.1.132:8088/WebServer/student.do"); // 打开连接 HttpURLConnection conn = (HttpURLConnection) url.openConnection(); // 设置访问超时时间 conn.setReadTimeout(5 * 1000); // 设置请求方式 conn.setRequestMethod("POST"); // 发送POST请求必须设置允许输出 conn.setDoOutput(true); conn.setRequestProperty("Charset", "utf-8"); conn.setRequestProperty("Content-Length", postData.length() + ""); OutputStream out = conn.getOutputStream(); out.write(postData.getBytes()); out.flush(); if (conn.getResponseCode() == 200) { InputStream in = conn.getInputStream(); // 从输入流中读取内容放到内存中 ByteArrayOutputStream out2 = new ByteArrayOutputStream(); byte[] buffer = new byte[1024]; int len = 0; while ((len = in.read(buffer)) != -1) { out2.write(buffer, 0, len); } System.out.println(new String(out2.toByteArray())); out2.close(); in.close(); } out.close(); }
在单元测试类MHttpclientTestCase再添加一个方法:
public void testPost() throws Exception { MHttpClient url = new MHttpClient(); url.post(); }
在方法名称右键->run as->android JUnit Test
可在logcat里看到返回结果 “11”
贴上全部代码:
MHttpClient.java
package org.example.httpclient; import java.io.ByteArrayOutputStream; import java.io.InputStream; import java.io.OutputStream; import java.net.HttpURLConnection; import java.net.URL; public class MHttpClient { public void get() throws Exception { // 实例化一个URL对象 URL url = new URL("http://192.168.1.132:8088/WebServer/student.do"); // 打开连接 HttpURLConnection conn = (HttpURLConnection) url.openConnection(); // 设置访问超时时间 conn.setConnectTimeout(5 * 1000); // 设置请求方式 conn.setRequestMethod("GET"); // 得到输入流 InputStream in = conn.getInputStream(); // 从输入流中读取内容放到内存中 ByteArrayOutputStream out = new ByteArrayOutputStream(); byte[] buffer = new byte[1024]; int len = 0; while ((len = in.read(buffer)) != -1) { out.write(buffer, 0, len); } System.out.println(new String(out.toByteArray())); out.close(); in.close(); } public void post() throws Exception { String postData = "name=11"; byte[] data = postData.getBytes(); // 实例化一个URL对象 URL url = new URL("http://192.168.1.132:8088/WebServer/student.do"); // 打开连接 HttpURLConnection conn = (HttpURLConnection) url.openConnection(); // 设置访问超时时间 conn.setConnectTimeout(10 * 1000); // 设置请求方式 conn.setRequestMethod("POST"); // 发送POST请求必须设置允许输出 conn.setDoOutput(true); conn.setRequestProperty("Charset", "UTF-8"); conn.setRequestProperty("Content-Length", data.length + ""); conn.setRequestProperty("Content-Type", "application/x-www-form-urlencoded"); conn.setRequestProperty("Connection", "Keep-Alive");// 维持长连接 OutputStream out = conn.getOutputStream(); out.write(data); out.flush(); if (conn.getResponseCode() == 200) { InputStream in = conn.getInputStream(); // 从输入流中读取内容放到内存中 ByteArrayOutputStream out2 = new ByteArrayOutputStream(); byte[] buffer = new byte[1024]; int len = 0; while ((len = in.read(buffer)) != -1) { out2.write(buffer, 0, len); } System.out.println(new String(out2.toByteArray())); out2.close(); in.close(); } out.close(); } }
MHttpclientTestCase.java
package org.example.httpclient; import android.test.AndroidTestCase; public class MHttpclientTestCase extends AndroidTestCase { public void testGet() throws Exception { MHttpClient url = new MHttpClient(); url.get(); } public void testPost() throws Exception { MHttpClient url = new MHttpClient(); url.post(); } }
AndroidManifest.xml