标签:urlconnection get post
conn.setRequestProperty("accept","*/*");
<?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.javapackage 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
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暗中执行了连接。Android 网络编程(3)——使用URLConnection提交请求
标签:urlconnection get post
原文地址:http://blog.csdn.net/thanksgining/article/details/43672259