HttpURLConnection用法詳解,包含代碼

1、參考資料

爲何要把參考資料放在前面,主要是方便你們資料閱讀。html

簡單介紹Java網絡編程中的HTTP請求
http://www.jb51.net/article/72651.htmjava

HttpURLConnection用法詳解
http://www.cnblogs.com/guodongli/archive/2011/04/05/2005930.html
http://0411.iteye.com/blog/1068297web

關於setConnectTimeout和setReadTimeout的問題
http://blog.csdn.net/jackson_wen/article/details/51923514編程

HTTP協議頭部與Keep-Alive模式詳解
http://blog.csdn.net/charleslei/article/details/50621912緩存

HttpURLConnection與HttpClient 區別、聯繫、性能對比
http://blog.csdn.net/u011479540/article/details/51918474
http://blog.csdn.net/zhou_wenchong/article/details/51243079
http://www.cnblogs.com/liushuibufu/p/4140913.html
http://blog.csdn.net/wszxl492719760/article/details/8522714服務器

其餘
http://blog.csdn.net/u012228718/article/details/42028951
http://www.jb51.net/article/73621.htm
http://blog.csdn.net/u012228718/article/details/42028951
http://blog.csdn.net/u011192000/article/details/47358933網絡

2、HttpURLConnection用法 代碼

一、UserInfo    rest服務器類,前一篇文章講解了如何搭建rest服務
二、HttpTools   http工具類,實現了doget與dopost方法
三、TestRest    測試類併發

如下代碼已經測試經過。app

UserInfo.java

package com.myrest;高併發

import java.io.UnsupportedEncodingException;
import java.net.URLDecoder;

import javax.ws.rs.GET;
import javax.ws.rs.POST;
import javax.ws.rs.Path;
import javax.ws.rs.PathParam;
import javax.ws.rs.Produces;
import javax.ws.rs.core.MediaType;

// 這裏@Path定義了類的層次路徑。
// 指定了資源類提供服務的URI路徑。
@Path("UserInfoService")
public class UserInfo {
    // @GET表示方法會處理HTTP GET請求
    @GET
    // 這裏@Path定義了類的層次路徑。指定了資源類提供服務的URI路徑。
    @Path("/name/{i}")
    // @Produces定義了資源類方法會生成的媒體類型。
    @Produces(MediaType.TEXT_XML)
    // @PathParam向@Path定義的表達式注入URI參數值。
    public String userName(@PathParam("i") String i) {
        // 發現get提交,會幫咱們自動解碼
        System.out.println("傳入 name:" + i);
        String name = "返回name:" + i;
        return name;
    }

    @POST
    @Path("/information/")
    public String userAge(String info) throws UnsupportedEncodingException {

        // post提交須要咱們手動解碼,避免中文亂碼
        String str = URLDecoder.decode(info, "UTF-8");
        System.out.println("傳入參數: " + info);
        System.out.println("解碼後參數: " + str);
        String value = "返回值:" + str;
        return value;
    }
}

 

HttpTools.java

package com.util;
import java.io.BufferedReader;
import java.io.ByteArrayOutputStream;
import java.io.DataOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.OutputStream;
import java.net.HttpURLConnection;
import java.net.URL;
import java.net.URLEncoder;
import java.util.Map;


public  final class HttpTools {
    private static final int CONNECT_TIMEOUT = 50000;
    private static final int READ_TIMEOUT = 30000;

    /**
     * 使用get請求方式請求數據,注意get傳遞中文字符須要用URLEncoder
     * @param urlPath 請求數據的URL
     * @return 返回字符串
     */
    public static String doGet(String urlPath){
        String ret=null;
        
        if(urlPath!=null){
            HttpURLConnection httpConn = null;
            try {
                // 創建鏈接
                URL url = new URL(urlPath);
                httpConn = (HttpURLConnection) url.openConnection();
                
                // 設置參數
                //httpConn.setDoOutput(true); // 須要輸出
                httpConn.setDoInput(true); // 須要輸入
                httpConn.setUseCaches(false); // 不容許緩存
                httpConn.setRequestMethod("GET"); // 設置POST方式鏈接
                
                // 設置請求屬性
//                httpConn.setRequestProperty("Content-Type", "application/x-java-serrialized-object");
                //設置請求體的類型是文本類型
                httpConn.setRequestProperty("Content-Type", "pplication/x-www-form-urlencoded");
                //維持長鏈接,這裏要注意,高併發不知道是否有bug
                httpConn.setRequestProperty("Connection", "Keep-Alive");
                httpConn.setRequestProperty("Charset", "UTF-8");
                
                //設置超時
                httpConn.setConnectTimeout(CONNECT_TIMEOUT); //鏈接超時時間
                httpConn.setReadTimeout(READ_TIMEOUT);    //傳遞數據的超時時間
                
                // 得到響應狀態
                int resultCode = httpConn.getResponseCode();
                if (HttpURLConnection.HTTP_OK == resultCode) {
                    InputStream inputStream=httpConn.getInputStream();
                    //處理返回結果
                    ret=dealResponseResult(inputStream);
                }
            } catch (Exception e) {
                e.printStackTrace();
            }
        }
        return ret;
    }
    
    public static String doPost(String urlPath,Map<String, String> params, String encode){
        String ret=null;
        
        byte[] data = getRequestData(params, encode).toString().getBytes();//得到請求體
        
        try {
            
            // 創建鏈接
            URL url = new URL(urlPath);
            HttpURLConnection httpConn = (HttpURLConnection) url.openConnection();
            
            // 設置參數
            httpConn.setDoOutput(true); // 須要輸出
            httpConn.setDoInput(true); // 須要輸入
            httpConn.setUseCaches(false); // 不容許緩存
            httpConn.setRequestMethod("POST"); // 設置POST方式鏈接
            
            // 設置請求屬性
//            httpConn.setRequestProperty("Content-Type", "application/x-java-serrialized-object");
             //設置請求體的類型是文本類型
            httpConn.setRequestProperty("Content-Type", "pplication/x-www-form-urlencoded");
            //設置請求體的長度,能夠不須要
            httpConn.setRequestProperty("Content-Length", String.valueOf(data.length));
            //維持長鏈接,這裏要注意,高併發不知道是否有bug
            httpConn.setRequestProperty("Connection", "Keep-Alive");
            httpConn.setRequestProperty("Charset", encode);
            
            //設置超時
            httpConn.setConnectTimeout(CONNECT_TIMEOUT); //鏈接超時時間
            httpConn.setReadTimeout(READ_TIMEOUT);    //傳遞數據的超時時間
            
            // 鏈接,也能夠不用明文connect,使用下面的httpConn.getOutputStream()會自動connect
            //httpConn.connect();
            
            // 創建輸入流,向指向的URL傳入參數
            DataOutputStream dos = new DataOutputStream(httpConn.getOutputStream());
            dos.write(data);
            dos.flush();
            dos.close();
            
            // 得到響應狀態
            int resultCode = httpConn.getResponseCode();
            if (HttpURLConnection.HTTP_OK == resultCode) {
                InputStream inputStream=httpConn.getInputStream();
                //處理返回結果
                ret=dealResponseResult(inputStream);
            }
            
            
        } catch (Exception e) {
              e.printStackTrace();
            return "err: " + e.getMessage().toString();
        }
        
        return ret;
        
    }


    /**
     * 封裝請求體信息
     * @param params 請求體 參數
     * @param encode 編碼格式
     * @return 返回封裝好的StringBuffer
     */
    public static StringBuffer getRequestData(Map<String, String> params, String encode) {
        StringBuffer stringBuffer = new StringBuffer();        //存儲封裝好的請求體信息
        try {
            for(Map.Entry<String, String> entry : params.entrySet()) {
                stringBuffer.append(entry.getKey())
                        .append("=")
                        .append(URLEncoder.encode(entry.getValue(), encode))
                        .append("&");
            }
            stringBuffer.deleteCharAt(stringBuffer.length() - 1);    //刪除最後的一個"&"
        } catch (Exception e) {
            e.printStackTrace();
        }
        return stringBuffer;
    }
    
    /**
     * 處理服務器返回結果
     * @param inputStream 輸入流
     * @return 返回處理後的String 字符串
     */
    public static String dealResponseResult(InputStream inputStream) {
        String value = null;  
       
        try {
            //存儲處理結果
            StringBuffer sb = new StringBuffer();
            String readLine = new String();
            BufferedReader responseReader = new BufferedReader(
                    new InputStreamReader(inputStream, "UTF-8"));
            while ((readLine = responseReader.readLine()) != null) {
                sb.append(readLine).append("\n");
            }
            responseReader.close();
            value=sb.toString();
        } catch (Exception e) {
            e.printStackTrace();
        }
        return value;
    }
}

 

TestRest.java

package com.myrest;

import java.io.BufferedReader;
import java.io.DataOutputStream;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.UnsupportedEncodingException;
import java.net.HttpURLConnection;
import java.net.URL;
import java.net.URLEncoder;
import java.util.HashMap;
import java.util.Map;

import com.util.HttpTools;

public class TestRest {

    public static void main(String[] args) throws IOException {
        testGet();
        testPost();
    }

    public static void testGet() throws IOException {
        String BASE_URI = "http://localhost:8080/webtest";
        String PATH_NAME = "/rest/UserInfoService/name/";
        String tmp = "奧特曼1號";
        // 漢字必須URL編碼,不然報錯。這裏用URLEncoder編碼,rest服務須要用URLDecoder解碼
        String name = URLEncoder.encode(tmp, "UTF-8");
        String urlPath = BASE_URI + PATH_NAME + name;
        String ret=HttpTools.doGet(urlPath);
        
        System.out.println(ret);

    }

    public static void testPost() throws IOException {
        String BASE_URI = "http://localhost:8080/webtest";
        String PATH_NAME = "/rest/UserInfoService/information/";
        String urlPath = BASE_URI + PATH_NAME;
        Map<String,String> params=new HashMap<String,String>();
        params.put("myParam", "我愛個人祖國!");
        
        String ret =HttpTools.doPost(urlPath, params, "utf-8");
        
        System.out.println(ret);

    } }

相關文章
相關標籤/搜索