码迷,mamicode.com
首页 > Web开发 > 详细

HttpClient之Http请求步骤

时间:2015-02-27 01:33:42      阅读:195      评论:0      收藏:0      [点我收藏+]

标签: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请求步骤

标签:android网络 httpclient

原文地址:http://craftsman001.blog.51cto.com/9187002/1615537

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!