URLConnection
URLConnection 相当于 URL 资源与应用程序之间的桥梁,作用与 JDBC 的 Connection 较为类似。HttpURLConnection 是 URLConnection 的子类,主要是建立 HTTP 上的连接,如访问网页资源。
使用 URLConnection 建立网络资源连接步骤:
1、调用 URL 类中的 OpenConnection 方法,获取 URLConnection 对象,如果 URL 创建时采用 HTTP,则可以直接强制转换为 HttpURLConnection 对象。
2、设置连接属性。
3、建立连接后,使用方法 getHeaderField() 和 getHeaderFieldKey(int posn) 可以查询头信息。
5、获取输入流,读取返回资源,该输入流与在 URL 中获取的输入流一致。
【注】
1、如果需要向 URL 发出请求参数,应该先使用输出流,后使用输入流。
2、联网的程序应写在子线程中,避免主线程被阻塞。

Get 与 Post 的区别
1、Get 将表单中的数据按照 variable = value 的形式,添加到 action 所指向的 URL 后面,并且两者使用 ? 连接,而各个变量之间使用 & 连接;如 urlStr = "http://192.168.1.103:8080/part10_3_3/servlet/LoginServlet?loginName=admin&loginPwd=admin")。Post 是将表单中的数据放在 form 的数据体中,按照变量和值相对应的方式,传递到 action 所指向的 URL。
2、Get 是不安全的,因为在传输过程中,数据被放在请求的 URL 中,是可见的(当然也可以采用加密的方法),而如今现有的很多服务器、代理服务器或者用户代理都会将请求 URL 记录到日志文件中,然后放在某个地方,这样就可能会有一些隐私的信息被第三方看到。另外,用户也可以在浏览器上直接看到提交的数据,一些系统内部消息将会一同显示在用户面前。Post 的所有操作对用户来说都是不可见的。
3、Get 传输的数据量小,这主要是因为受 URL 长度限制,不同浏览器大小限制有所不同,一般不超过 2KB 都不会出问题;而 Post 可以传输大量的数据,所以在上传文件时只能使用 Post。
4、Get 现在 Form 表单的数据集的值必须为 ASCII 字符;而 Post 支持整个 ISO10646 字符集。默认使用 ISO-8859-1 编码。
客户端
 
1 import java.io.BufferedReader; 2 import java.io.IOException; 3 import java.io.InputStreamReader; 4 import java.io.PrintWriter; 5 import java.net.HttpURLConnection; 6 import java.net.MalformedURLException; 7 import java.net.URL; 8 9 import android.os.Bundle; 10 import android.os.Handler; 11 import android.os.Message; 12 import android.app.Activity; 13 import android.util.Log; 14 import android.view.Menu; 15 import android.view.View; 16 import android.view.View.OnClickListener; 17 import android.widget.Button; 18 import android.widget.TextView; 19 20 public class MainActivity extends Activity implements OnClickListener { 21 22 Button b1,b2; 23 TextView tv; 24 String urlStr = "http://192.168.1.103:8080/part10_3_3/servlet/LoginServlet"; 25 26 Handler handler = new Handler(){ 27 @Override 28 public void handleMessage(Message msg) { 29 super.handleMessage(msg); 30 Bundle b = msg.getData(); 31 tv.append(b.getString("msg") + "\n"); 32 } 33 }; 34 35 @Override 36 protected void onCreate(Bundle savedInstanceState) { 37 super.onCreate(savedInstanceState); 38 39 setContentView(R.layout.activity_main); 40 b1 = (Button) findViewById(R.id.bt_get); 41 b2 = (Button) findViewById(R.id.bt_post); 42 tv = (TextView) findViewById(R.id.tv); 43 b1.setOnClickListener(this); 44 b2.setOnClickListener(this); 45 } 46 47 @Override 48 public void onClick(View arg0) { 49 50 if(arg0.getId() == R.id.bt_get){ 51 // 发起 Get 请求 52 getRequest(); 53 }else { 54 // 发起 Post 请求 55 postRequest(); 56 } 57 } 58 //Get 方式 59 public void getRequest(){ 60 61 final String us = urlStr + "?loginName=admin&loginPwd=admin"; 62 new Thread (new Runnable(){ 63 @Override 64 public void run() { 65 BufferedReader br = null; 66 try { 67 // Step1 创建 URL 68 URL url = new URL(us); 69 // Step2 获取 HttpURLConnection 对象 70 HttpURLConnection httpConn = (HttpURLConnection) url.openConnection(); 71 // Step3 设置属性 72 httpConn.setRequestProperty("accept", "*/*"); 73 httpConn.setDoInput(true); 74 httpConn.setDoOutput(true); 75 httpConn.setConnectTimeout(5000); 76 // Step4 连接 77 httpConn.connect(); 78 // Step5 获取连续属性 79 int stat = httpConn.getResponseCode(); 80 String ss = httpConn.getResponseMessage(); 81 Log.i("Tag", "服务器返回代码" + stat + " ," + ss); 82 // Step6 读取返回数据 83 String msg = ""; 84 if(stat == 200){ 85 br = new BufferedReader( 86 new InputStreamReader(httpConn.getInputStream())); 87 msg = br.readLine(); 88 }else{ 89 msg = "请求失败..."; 90 } 91 Bundle b = new Bundle(); 92 b.putString("msg", msg); 93 Message m = new Message(); 94 m.setData(b); 95 handler.sendMessage(m); 96 } catch (MalformedURLException e) { 97 // TODO Auto-generated catch block 98 e.printStackTrace(); 99 } catch (IOException e) { 100 // TODO Auto-generated catch block 101 e.printStackTrace(); 102 }finally{ 103 if(br != null) 104 try { 105 br.close(); 106 } catch (IOException e) { 107 // TODO Auto-generated catch block 108 e.printStackTrace(); 109 } 110 } 111 } 112 }).start(); 113 } 114 115 // Post 方式 116 public void postRequest(){ 117 new Thread (new Runnable(){ 118 @Override 119 public void run() { 120 PrintWriter pw = null; 121 BufferedReader br = null; 122 try { 123 URL url = new URL(urlStr); 124 HttpURLConnection httpConn = (HttpURLConnection) url.openConnection(); 125 httpConn.setRequestProperty("accept", "*/*"); 126 httpConn.setDoInput(true); 127 httpConn.setDoOutput(true); 128 httpConn.setConnectTimeout(5000); 129 //httpConn.connect(); 130 // 发送请求参数 131 pw = new PrintWriter(httpConn.getOutputStream()); 132 pw.println("loginName=admin&loginPwd=admin"); 133 pw.flush(); 134 int stat = httpConn.getResponseCode(); 135 String ss = httpConn.getResponseMessage(); 136 Log.i("Tag", "服务器返回代码 " + stat + " ," + ss); 137 // 读取响应 138 String msg = ""; 139 if(stat == 200){ 140 br = new BufferedReader(new InputStreamReader(httpConn.getInputStream())); 141 msg = br.readLine(); 142 }else{ 143 msg = "请求失败..."; 144 } 145 Bundle b = new Bundle(); 146 b.putString("msg", msg); 147 Message m = new Message(); 148 m.setData(b); 149 handler.sendMessage(m); 150 } catch (MalformedURLException e) { 151 // TODO Auto-generated catch block 152 e.printStackTrace(); 153 } catch (IOException e) { 154 // TODO Auto-generated catch block 155 e.printStackTrace(); 156 } 157 } 158 }).start(); 159 } 160 }
布局文件
 
1 <RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android" 2 xmlns:tools="http://schemas.android.com/tools" 3 android:layout_width="match_parent" 4 android:layout_height="match_parent" 5 android:paddingBottom="@dimen/activity_vertical_margin" 6 android:paddingLeft="@dimen/activity_horizontal_margin" 7 android:paddingRight="@dimen/activity_horizontal_margin" 8 android:paddingTop="@dimen/activity_vertical_margin" 9 tools:context=".MainActivity" > 10 <LinearLayout 11 android:id="@+id/layout" 12 android:layout_width="fill_parent" 13 android:layout_height="wrap_content" 14 android:orientation="horizontal" 15 android:gravity="center_horizontal" 16 > 17 <Button 18 android:id="@+id/bt_get" 19 android:layout_width="wrap_content" 20 android:layout_height="wrap_content" 21 android:text="Get请求" 22 /> 23 <Button 24 android:id="@+id/bt_post" 25 android:layout_width="wrap_content" 26 android:layout_height="wrap_content" 27 android:text="Post请求" 28 /> 29 </LinearLayout> 30 31 <TextView 32 android:id="@+id/tv" 33 android:layout_width="fill_parent" 34 android:layout_height="wrap_content" 35 android:layout_below="@id/layout" 36 /> 37 38 </RelativeLayout>
网络权限
<uses-permission android:name="android.permission.INTERNET"/>
服务端是部署在 Tomat 上的一个 Servlet,MyEclipse 程序
 
1 import java.io.IOException; 2 import java.io.PrintWriter; 3 4 import javax.servlet.ServletException; 5 import javax.servlet.http.HttpServlet; 6 import javax.servlet.http.HttpServletRequest; 7 import javax.servlet.http.HttpServletResponse; 8 9 public class LoginServlet extends HttpServlet { 10 11 /** 12 * The doGet method of the servlet. <br> 13 * 14 * This method is called when a form has its tag value method equals to get. 15 * 16 * @param request the request send by the client to the server 17 * @param response the response send by the server to the client 18 * @throws ServletException if an error occurred 19 * @throws IOException if an error occurred 20 */ 21 public void doGet(HttpServletRequest request, HttpServletResponse response) 22 throws ServletException, IOException { 23 24 response.setCharacterEncoding("UTF-8"); 25 String ln=request.getParameter("loginName"); 26 String lp=request.getParameter("loginPwd"); 27 System.out.println("服务器端,doPost执行。登录名:密码-->"+ln+":"+lp); 28 29 response.setContentType("text/html"); 30 PrintWriter out = response.getWriter(); 31 out.println("服务器端,doGet执行。登录名:密码-->"+ln+":"+lp); 32 out.flush(); 33 out.close(); 34 } 35 36 /** 37 * The doPost method of the servlet. <br> 38 * 39 * This method is called when a form has its tag value method equals to post. 40 * 41 * @param request the request send by the client to the server 42 * @param response the response send by the server to the client 43 * @throws ServletException if an error occurred 44 * @throws IOException if an error occurred 45 */ 46 public void doPost(HttpServletRequest request, HttpServletResponse response) 47 throws ServletException, IOException { 48 49 response.setCharacterEncoding("UTF-8"); 50 String ln=request.getParameter("loginName"); 51 String lp=request.getParameter("loginPwd"); 52 System.out.println("服务器端,doPost执行。登录名:密码-->"+ln+":"+lp); 53 54 response.setContentType("text/html"); 55 PrintWriter out = response.getWriter(); 56 out.println("服务器端,doPost执行。登录名:密码-->"+ln+":"+lp); 57 out.flush(); 58 out.close(); 59 } 60 61 }
 
                    
                
 
 
 
                
            
         浙公网安备 33010602011771号
浙公网安备 33010602011771号