HttpClient之Http請求步驟

來源:互聯網
上載者:User

標籤:android網路 httpclient

        apache為用戶端http請求提供了一套有用的API,在安卓端編寫http請求操作的時候可以使用該API,下面總結一下請求步驟.

壹.建立List<NameValuePair>對象,為表單提供用list存放的參數:

List<NameValuePair> list=getRequestParams(requestParams);

//將請求的Map轉換成List

 private static List<NameValuePair> getRequestParams(Map<String,String> requestParams){

        List<NameValuePair> list=null;

        list=new ArrayList<NameValuePair>();

        //產生迭代器

        Iterator iterator=requestParams.entrySet().iterator();

        while (iterator.hasNext()){

            //Map.Entry介面,將索引值對分隔

            Map.Entry<String,String>entry =(Map.Entry<String,String>)iterator.next();

            list.add(new BasicNameValuePair(entry.getKey(),entry.getValue()));

        }

        return list;

    }

貳.用singleton模式建立httpclient對象:

 HttpClient mHttpClient =SingleTonHttpClients.getInstanceHttpClients();


public class SingleTonHttpClients {

    private SingleTonHttpClients(){}

    private static final HttpClient mHttpClient=new DefaultHttpClient();

    public static HttpClient getInstanceHttpClients(){

        return mHttpClient;

    }

}

三.建立HttpPost對象,以post形式提交表單:

 HttpPost post=buildHttpPost(list,requestPath);


private static HttpPost buildHttpPost(List<NameValuePair> list,String requestPath){

        HttpPost post=null;

        try{

            UrlEncodedFormEntity postEntity=new UrlEncodedFormEntity(list,"utf-8");

            post=new HttpPost(requestPath);

            post.setEntity(postEntity);

        }

        catch (UnsupportedEncodingException e){

            e.printStackTrace();

        }

        return post;

    }


肆.執行post方法,請求伺服器,返回資料流(建立HttpResponse對象,用以接收伺服器返回;HttpEntity對象,用以得到伺服器返回內容並以流的形式返回)

 InputStream serverInputStream =getSeverResponse(mHttpClient,post)


 private static InputStream getSeverResponse(HttpClient mHttpClient,HttpPost post){

        try {

            HttpResponse mResponse=mHttpClient.execute(post);

            HttpEntity mEntity=mResponse.getEntity();

            return mEntity.getContent();

        }

        catch (SocketTimeoutException e){

            e.printStackTrace();

        }

        catch (IOException e){

            e.printStackTrace();

        }

        return null;

    }

伍.將輸入資料流讀入,並處理成字串

 private static InputStream getSeverResponse(HttpClient mHttpClient,HttpPost post)


 private static InputStream getSeverResponse(HttpClient mHttpClient,HttpPost post){

        try {

            HttpResponse mResponse=mHttpClient.execute(post);

            HttpEntity mEntity=mResponse.getEntity();

            return mEntity.getContent();

        }

        catch (SocketTimeoutException e){

            e.printStackTrace();

        }

        catch (IOException e){

            e.printStackTrace();

        }

        return null;

    }


完整代碼如下:

public class HttpUtils {

    /**

     *

     * @param requestPath 伺服器請求路徑

     * @param requestParams 請求參數

     * @param requestEncode 請求表單的編碼格式

     * @param responseEncode 請求返回體的編碼格式

     * @return

     */

    public static String getResponseString(String requestPath,

        Map<String,String>requestParams,String requestEncode,String responseEncode){

        //將請求參數轉換成list

        List<NameValuePair> list=getRequestParams(requestParams);

        if(list!=null) {

            //建立HttpPost對象,以post形式提交表單

            HttpPost post=buildHttpPost(list,requestPath);

            //建立httpclient對象

            HttpClient mHttpClient =SingleTonHttpClients.getInstanceHttpClients();

            if(mHttpClient!=null){

                //將伺服器返回結果以流的形式讀取

                InputStream serverInputStream =getSeverResponse(mHttpClient,post);

                if (serverInputStream!=null){

                    //將伺服器返回結果轉換成字串

                    return (getStreamToString(serverInputStream,responseEncode));

                }

                else {

                    return "internetexception";

                }

            }

            else {

                return "singletonexception";

            }


        }

        else return "paramsexception";

    }


    /**

     * 將請求的Map轉換成List

     * @param requestParams

     * @return

     */

    private static List<NameValuePair> getRequestParams(Map<String,String> requestParams){

        List<NameValuePair> list=null;

        list=new ArrayList<NameValuePair>();

        //產生迭代器

        Iterator iterator=requestParams.entrySet().iterator();

        while (iterator.hasNext()){

            //Map.Entry介面,將索引值對分隔

            Map.Entry<String,String>entry =(Map.Entry<String,String>)iterator.next();

            list.add(new BasicNameValuePair(entry.getKey(),entry.getValue()));

        }

        return list;

    }


    /**

     * 將list放入請求表單中

     * 執行個體化HttpPost對象

     * @param list

     * @param requestPath

     * @return

     */

    private static HttpPost buildHttpPost(List<NameValuePair> list,String requestPath){

        HttpPost post=null;

        try{

            UrlEncodedFormEntity postEntity=new UrlEncodedFormEntity(list,"utf-8");

            post=new HttpPost(requestPath);

            post.setEntity(postEntity);

        }

        catch (UnsupportedEncodingException e){

            e.printStackTrace();

        }

        return post;

    }


    /**

     * 執行post方法,請求伺服器,返回資料流

     * @param mHttpClient

     * @param post

     * @return

     */

    private static InputStream getSeverResponse(HttpClient mHttpClient,HttpPost post){

        try {

            HttpResponse mResponse=mHttpClient.execute(post);

            HttpEntity mEntity=mResponse.getEntity();

            return mEntity.getContent();

        }

        catch (SocketTimeoutException e){

            e.printStackTrace();

        }

        catch (IOException e){

            e.printStackTrace();

        }

        return null;

    }


    /**

     * 將網路中的資料流轉換成字串

     * @param inputStream

     * @param encode

     * @return

     */

    private static String getStreamToString(InputStream inputStream,String encode){

        StringBuffer stringBuffer=new StringBuffer();

        try {

            BufferedReader mBufferedReader=new BufferedReader(new InputStreamReader(inputStream,encode));

            String tmp=new String();

            while ((tmp=mBufferedReader.readLine())!=null){

                stringBuffer.append(tmp);

            }

            mBufferedReader.close();

            return stringBuffer.toString();

        }

        catch (UnsupportedEncodingException e){

            e.printStackTrace();

            return "switchexception";

        }

        catch (IOException e){

            e.printStackTrace();

            return "switchexception";

        }

    }

}


HttpClient之Http請求步驟

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.