Android 网络编程(3)——使用URLConnection提交请求
- 通过调用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发送请求参数
- getContentEncoding:获取content-enconding响应头字段的值
- getContentLength:获取content-length响应头字段的值
- getContentType:获取content-type响应头字段的值
- getDate():获取date响应头字段的值
- getExpiration():获取expires响应头字段的值
- getLastModified():获取last-modified响应头字段的值
<?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】按钮,打印信息
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();
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暗中执行了连接。
郑重声明:本站内容如果来自互联网及其他传播媒体,其版权均属原媒体及文章作者所有。转载目的在于传递更多信息及用于网络分享,并不代表本站赞同其观点和对其真实性负责,也不构成任何其他建议。