1. 程式人生 > >HttpURLConnection傳送POST資料

HttpURLConnection傳送POST資料

一、步驟分為

1.通過String型別的URL地址或者是String protocol, String host, int port, String file各字串值得到URL物件

2、通過URL物件得到HTTPURLConnection

3、通過httpURLConnection物件得到請求的返回值

二、得到URL的三種方式(推薦使用第一種)

1、public URL(String url) 

2、public URL(String protocol, String host, int port, String file)//可自定義請求的埠

3、public URL(String protocol, String host, String file)//預設埠為80

三、得到URLConnection物件

URLConnection urlConnection=url.openConnection();
if(urlConnection instanceof HttpURLConnection)

httpURLConnection=(HttpURLConnection) urlConnection;

四、 通過URLConnection物件得到結果的輸入流
InputStream is=urlConnection.getInputStream();

DEMO如下:

I.封裝類

package url;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.net.HttpURLConnection;
import java.net.MalformedURLException;
import java.net.URL;
import java.net.URLConnection;
import java.util.Iterator;
import java.util.Map;
import java.util.Set;

public class URLUtils {
	/*
	 * 獲取URL通過URL路徑
	 */
	public static URL getURL(String strUrl)
	{
		try {
			URL url=new URL(strUrl);
			return url;
		} catch (MalformedURLException e) {
			System.out.println("通過地址得到URL出現異常...");
			e.printStackTrace();
			return null;
		}
	}
	
	/*
	 * 通過URL物件獲取Connection連結
	 */
	public static URLConnection getConnectionByURL(URL url,String params)
	{
		HttpURLConnection httpURLConnection=null;
		try {
			URLConnection urlConnection=url.openConnection();
			if(urlConnection instanceof HttpURLConnection)
				httpURLConnection=(HttpURLConnection) urlConnection;
			/*
			 * 設定請求的方式和一些其他的引數
			 */
			httpURLConnection.setDoInput(true);   //需要輸入
			httpURLConnection.setUseCaches(false);  //不允許快取
			httpURLConnection.setRequestMethod("POST");   //設定POST方式連線
		    //設定請求屬性
			httpURLConnection.setRequestProperty("Content-Type", "application/x-www-form-urlencoded");
			httpURLConnection.setRequestProperty("Connection", "Keep-Alive");// 維持長連線
			httpURLConnection.setRequestProperty("Charset", "UTF-8");
			
			httpURLConnection.setDoOutput(true);//允許傳入引數
			byte[] paramByte=params.getBytes();
			//引數值不要第一個的  ? 號值
			httpURLConnection.getOutputStream().write(paramByte);//傳入引數的byte型別
			return httpURLConnection;
		} catch (IOException e) {
			System.out.println("獲取連線異常...");
			e.printStackTrace();
			return null;
		}
	}
	
	/*
	 * 通過URLConnection 物件得到請求的返回值
	 */
	public static String getResponseValue(URLConnection urlConnection) 
	{
		String result="";
		try {
			InputStream is=urlConnection.getInputStream();
			
			BufferedReader in = new BufferedReader(
			         new InputStreamReader(is));
			String current;
			while((current = in.readLine()) != null)
			{
				result += current;
			}
			return result;
		} catch (IOException e) {
			System.out.println("請求結果讀取異常...");
			e.printStackTrace();
			return result;
		}
	}
	
	/*
	 * 將Map型別的引數值轉為String型別
	 */
	public static String mapToString(Map<String,Object> param)
	{
		StringBuffer sb=new StringBuffer("");
		if(param==null||param.size()==0)
			return sb.toString();
		else
		{
			int index=1;
			Set<String> keySet=param.keySet();
			Iterator<String> keys=keySet.iterator();
			while(keys.hasNext())
			{
				String key=keys.next();
				String value=(String) param.get(key);
				if(index==1)
				{					
					sb.append(key+"="+value);
				}else
				{
					sb.append("&"+key+"="+value);
				}
				index+=1;
			}
			return sb.toString();
		}
		
	}
	
	
	
}

II.測試類

package url;

import java.net.URL;
import java.net.URLConnection;
import java.util.HashMap;
import java.util.Map;

public class URLMain {

	public static void main(String[] args) {
		String url="你需要請求的URL連線";
		URL obj=URLUtils.getURL(url);
		Map<String,Object> map=new HashMap<String,Object>();
		//可定義多個引數值 以鍵值對的方式放入map中  也可使用其他的方式  
		map.put("websiteNo", "ffb6ccf64b");
		String params=URLUtils.mapToString(map);
		URLConnection urlConnection=URLUtils.getConnectionByURL(obj,params);
		String result=URLUtils.getResponseValue(urlConnection);
		System.out.println("請求結果: "+result);
		
	}

}
注.若是以GET的方式請求,則可以將引數直接拼接在URL地址後面,修改下面程式碼
httpURLConnection.setRequestMethod("GET");   //設定GET方式連線