Android 网络编程(三)——使用URLConnection提交请求
Android 网络编程(3)——使用URLConnection提交请求

第一步是creat:URLConnection urlConnect = url.openConnection();
URL的openConnection()方法将返回一个URLConnection对象,该对象表示应用程序和URL之间的通信连接。程序可以通过URLConnection实例向该URL发送请求,读取URL引用的资源
通常创建一个和URL的连接,并发送请求、读取此URL引用的资源需要如下几个步骤:
- 通过调用URL对象openConnection()方法来创建URLConnection对象
- 设置URLConnection的参数和普通请求属性
- 如果只是发送GET方法请求,使用connect方式建立和远程资源之间的实际连接即可;如果需要发送POST方式的请求,需要获取URLConnection实例对应的输出流来发送请求参数
- 远程资源变为可用,程序可以访问远程资源的头字段,或通过输入流读取远程资源的数据
在建立和远程资源的实际连接之前,程序可以通过如下方法来设置请求头字段
- setAllowUserInteraction:设置该URLConnection的allowUserInteraction请求头字段的值
- setDoInput:设置该URLConnection的doinput请求头字段的值
- setDoOutput:设置该URLConnection的dooutput请求头字段的值
- setIfModifiedSince:设置该URLConnection的ifModifiedSince请求头字段的值
- setUseCaches:设置该URLConnection的useCaches请求头字段的值
除此之外,还可以使用如下方法来设置或增加通用头字段
- setRequestProperty(String key, String value):设置该URLConnection的key请求头字段的值为value,如以下代码所示:
conn.setRequestProperty("accept","*/*");
- addRequestProperty(String key, String value):为该URLConnection的key请求头字段的增加value值,该方法并不会覆盖原请求头字段的值,而是将新值追加到原请求头字段中
当远程资源可用之后,程序可以使用以下方法用于访问头字段和内容
- Object getContent():获取该URLConnection的内容
- String getHeaderField(String name):获取指定响应头字段的值
- getInputStream():返回该URLConnection对应的输入流,用于获取URLConnection响应的内容
- getOutputStream():返回该URLConnection对应的输出流,用于向URLConnection发送请求参数
如果既要使用输入流读取URLConnection响应的内容,也要使用输出流发送请求参数,一定要先使用输出流,在使用输入流
getHeaderField()方法用于根据响应头字段来返回对应的值。而某些头字段由于经常需要访问,所有Java提供了以下方法来访问特定响应头字段的值
- getContentEncoding:获取content-enconding响应头字段的值
- getContentLength:获取content-length响应头字段的值
- getContentType:获取content-type响应头字段的值
- getDate():获取date响应头字段的值
- getExpiration():获取expires响应头字段的值
- getLastModified():获取last-modified响应头字段的值
URL请求的类别:分为二类,GET和POST请求。二者的区别在于:
1)、get请求可以获取静态页面,也可以把参数放在URL字符串后面,传递给servlet(利用java编写的服务端程序)
2)、post与get的不同之处在post的参数不是放在URL字符串里面,而是放在http请求的正文内。
post请求可以向服务器传送数据,而且数据放在HTML HEADER内一起传送到服务器URL地址,数据对用户不可见。而get是把参数数据队列加到提交的URL中,值和表单内各各个字段一一对应,例如(http://www.baidu.com/s?w=%C4&inputT=2710)。get请求机制用的是URL地址里面,通过?号间隔,然后以name=value的形式给客户端传递参数。
get传送的数据量较小,不能大于2KB。post传送的数据量较大,一般被默认不受限制。但理论上,IIS4中最大量为80KB,IIS5中为100KB。
get安全性非常低,post安全性较高。
例子:使用URLConnection提交请求
AndroidManifest.xml——主要添加访问网络权限
<?xml version="1.0" encoding="utf-8"?> <manifest xmlns:android="http://schemas.android.com/apk/res/android" package="com.example.url_get_post" android:versionCode="1" android:versionName="1.0" > <uses-sdk android:minSdkVersion="8" android:targetSdkVersion="19" /> <uses-permission android:name="android.permission.INTERNET"/> <application android:allowBackup="true" android:icon="@drawable/ic_launcher" android:label="@string/app_name" android:theme="@style/AppTheme" > <activity android:name="com.example.url_get_post.MainActivity" android:label="@string/app_name" > <intent-filter> <action android:name="android.intent.action.MAIN" /> <category android:name="android.intent.category.LAUNCHER" /> </intent-filter> </activity> </application> </manifest>activity_main.xml
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android" xmlns:tools="http://schemas.android.com/tools" android:layout_width="match_parent" android:layout_height="match_parent" android:gravity="center" android:orientation="vertical" tools:context=".MainActivity" > <Button android:id="@+id/get" android:layout_width="wrap_content" android:layout_height="wrap_content" android:background="#00ffff" android:text="get"/> <Button android:id="@+id/post" android:layout_width="wrap_content" android:layout_height="wrap_content" android:layout_marginTop="40dp" android:background="#00ffff" android:text="post"/> </LinearLayout>GetPostUtil.java——get和post两种请求方式
package com.example.url_get_post; import java.io.BufferedReader; import java.io.IOException; import java.io.InputStreamReader; import java.io.PrintWriter; import java.net.MalformedURLException; import java.net.URL; import java.net.URLConnection; import java.util.List; import java.util.Map; import android.util.Log; public class GetPostUtil { /** * 向指定URL发送GET方法的请求 * @param url 发送请求的URL * @param parmas 请求参数,请求参数应该是name1=value1&name2=value2的形式 * @return URL所代表远程资源的响应 */ public static String sendGet(String url, String parmas){ String result = ""; BufferedReader bufferedReader = null; String urlName = url + "?" + parmas; try { URL realUrl = new URL(urlName); //打开和URL之间的连接 try { URLConnection urlConnection = realUrl.openConnection(); /*设置通用请求属性*/ //告诉WEB服务器自己接受什么介质类型,*/* 表示任何类型,type/* 表示该类型下的所有子类型,type/sub-type。 urlConnection.setRequestProperty("accept", "*/*"); urlConnection.setRequestProperty("connection", "Keep-Alive"); //浏览器表明自己的身份(是哪种浏览器) urlConnection.setRequestProperty("user-agent", "Mozilla/5.0 (Windows; U; Windows NT 5.1; zh-CN; rv:1.8.1.14)"); //建立实际连接 urlConnection.connect(); Log.e("contentType", ""+urlConnection.getContentType()); Log.e("contentLength", ""+urlConnection.getContentLength()); Log.e("contentEncoding", ""+urlConnection.getContentEncoding()); Log.e("contentDate", ""+urlConnection.getDate()); //获取所有相应头字段 Map<String, List<String>> map = urlConnection.getHeaderFields(); //遍历所有响应头字段 for (String key:map.keySet()){ Log.i("GET方式请求", ""+map.get(key)); } //定义BufferReader输入流来读取URL的响应 bufferedReader = new BufferedReader(new InputStreamReader(urlConnection.getInputStream())); String line; for (;(line = bufferedReader.readLine()) != null;){ result += "\n" + line; } } catch (IOException e) { // TODO Auto-generated catch block Log.e("GET方式请求", "发送GET请求异常"+e); e.printStackTrace(); } } catch (MalformedURLException e) { // TODO Auto-generated catch block e.printStackTrace(); } finally { if (null != bufferedReader){ try { bufferedReader.close(); } catch (IOException e) { // TODO Auto-generated catch block e.printStackTrace(); } } } return result; } /** * 向指定URL发送POST方法的请求 * @param url 发送请求的URL * @param parmas 请求参数,请求参数应该是name1=value1&name2=value2的形式 * @return URL所代表远程资源的响应 */ public static String sendPost(String url, String parmas){ String result = ""; PrintWriter printWriter = null; BufferedReader bufferedReader = null; try { URL realUrl = new URL(url); //打开和URL之间的连接 try { URLConnection urlConnection = realUrl.openConnection(); //设置通用请求属性 urlConnection.setRequestProperty("accept", "*/*"); urlConnection.setRequestProperty("connection", "Keep-Alive"); urlConnection.setRequestProperty("user-agent", "Mozilla/4.0(compatible; MSIE 6.0; Windows NT 5.1; SV1)"); //发送POST请求必须设置如下两行 urlConnection.setDoOutput(true); urlConnection.setDoInput(true); //获取所有相应头字段 Map<String, List<String>> map = urlConnection.getHeaderFields(); //遍历所有响应头字段 for (String key:map.keySet()){ Log.i("POST方式请求", ""+map.get(key)); } //获取URLConnection对象对应的输出流 printWriter = new PrintWriter(urlConnection.getOutputStream()); //发送请求参数 printWriter.print(parmas); //flush输出流缓冲 printWriter.flush(); //定义BufferReader输入流来读取URL的响应 bufferedReader = new BufferedReader(new InputStreamReader(urlConnection.getInputStream())); String line; for (;(line = bufferedReader.readLine()) != null;){ result += "\n" + line; } } catch (IOException e) { // TODO Auto-generated catch block Log.e("GET方式请求", "发送GET请求异常"+e); e.printStackTrace(); } } catch (MalformedURLException e) { // TODO Auto-generated catch block e.printStackTrace(); } finally { if (null != bufferedReader){ try { bufferedReader.close(); } catch (IOException e) { // TODO Auto-generated catch block e.printStackTrace(); } } if (null != printWriter){ printWriter.close(); } } return result; } }MainActivity.java
package com.example.url_get_post; import android.os.Bundle; import android.util.Log; import android.view.View; import android.widget.Button; import android.app.Activity; public class MainActivity extends Activity { private Button get,post; private String response; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); get = (Button)this.findViewById(R.id.get); post = (Button)this.findViewById(R.id.post ); get.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View arg0) { // TODO Auto-generated method stub new Thread(){ @Override public void run() { response = GetPostUtil.sendGet("http://www.jju.edu.cn/", null); Log.i("response", response); }; }.start(); } }); post.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View arg0) { // TODO Auto-generated method stub new Thread(){ @Override public void run() { response = GetPostUtil.sendPost("http://www.jju.edu.cn/", null); // Log.i("response", response); }; }.start(); } }); } }点击【get】按钮,打印信息
点击【post】按钮,打印信息
头字段信息都是一样的,对于post出现的异常,还没有找到原因,先记录下。在这里希望大神们,指点小弟我!!!还是因为我所用的网站是我学校的网站,不能write请求?
urlConnection.setDoOutput(true);// 使用 URL 连接进行输出 urlConnection.setDoInput(true);// 使用 URL 连接进行输入
<strong>下面有关创建URLconnection对象,与服务器之间建立连接过程</strong>:来自:http://www.cnblogs.com/shyang--TechBlogs/archive/2011/03/21/1990525.html
第一步是creat:URLConnection urlConnect = url.openConnection();
第二步是connect:urlConnection.connect();//这两个是不同的
在created和connected之间可以设置一些变量选项(如setDoInput,超时等),而如果connect之后再设置就会引发异常
在需要连接才能执行的操作(如getInputStream等应用层操作),程序会暗中(implicitly)执行连接。一旦连接可用,就可以访问获取资源,如执行getInputStream()等,对于HTTPURLConnect,还有conn。getResponseCode()==200来判断服务器是否返回正确的应答码以表明请求被接受。
在URLConnection中,有一个域boolean connected,值为true表明已经建立到指定URL的连接,false则没有。
connect()当连接还未建立时,打开一个communications link,而如果这个链接已经被打开(connect值设置为true),否则ignore it
URL url = new URL("http://www.google.cn"); URLConnection conn = url.openConnection(); conn.setConnectTimeout(10000); conn.connect(); InputStream inStream = conn.getInputStream();当执行执行完openConnection()之后,域connected值还是false,说明这时候还未连接。等执行到connect()之后,connected才变为true,说明这时候才完成连接。而当注释掉connect()之后,在运行程序,connected值到getInputStream执行完又变为true,getInputStream暗中执行了连接。