Android中HttpURLConnection实现HTTP请求

本文实现了用HttpURLConnection实现HTTP请求,主要是用户API接口的访问。


1、实现参数map容器拼接成字符串,加上参数格式化编码

/**
     * <将map拼接成url参数>
     * <功能详细描述>
     * @param params
     * @param encode
     * @return
     * @throws UnsupportedEncodingException
     * @see [类、类#方法、类#成员]
     */
    public static String paramsToString(Map<String, String> params, String encode) throws UnsupportedEncodingException{
        String paramStr = "";
        if(params!=null){
            Iterator<Entry<String, String>> iter = params.entrySet().iterator();
            while (iter.hasNext())
            {
                Map.Entry<String, String> entry = (Map.Entry<String, String>)iter.next();
                String key = URLEncoder.encode(entry.getKey(), encode);
                String val = URLEncoder.encode(entry.getValue(), encode);
                paramStr += paramStr = "&" + key + "=" + val;
            }
            if (!paramStr.equals(""))
            {
                paramStr = paramStr.replaceFirst("&", "");
            }
        }
        return paramStr;
    }


对于get请求,结合传入的url可以直接拼接成需要请求的url地址

/**
     * <拼接参数到url上>
     * <功能详细描述>
     * @param url
     * @param params
     * @param encode
     * @return
     * @throws UnsupportedEncodingException
     * @see [类、类#方法、类#成员]
     */
    public static String encodeParams(String url, Map<String, String> params, String encode)
        throws UnsupportedEncodingException
    {
        String paramStr =paramsToString(params, encode); 
        if(!"".equals(paramStr)){
            url=url+"?"+paramStr;
        }
        return url;
    }

2、get请求服务器

/**
     * <get请求服务器>
     * <功能详细描述>
     * @param url
     * @param params
     * @param encode
     * @return
     * @throws UnsupportedEncodingException 
     * @see [类、类#方法、类#成员]
     */
    public static String doGet(String url, Map<String, String> params, String encode) throws UnsupportedEncodingException
    {
        url = encodeParams(url, params, encode);
        String result = null;
        HttpURLConnection connection = null;
        InputStreamReader in = null;
        try
        {
            URL httpUrl = new URL(url);
            connection = (HttpURLConnection)httpUrl.openConnection();
            connection.setRequestMethod("GET");
            connection.setConnectTimeout(TIME);
            connection.setReadTimeout(TIME);
            int responseCode = connection.getResponseCode();
            if(responseCode == HttpURLConnection.HTTP_OK){
                in = new InputStreamReader(connection.getInputStream());
                BufferedReader bufferedReader = new BufferedReader(in);
                StringBuffer strBuffer = new StringBuffer();
                String line = null;
                while ((line = bufferedReader.readLine()) != null)
                {
                    strBuffer.append(line);
                }
                result = URLDecoder.decode(strBuffer.toString(), encode);
            }
        }
        catch (Exception e)
        {
            e.printStackTrace();
        }
        finally
        {
            if (connection != null)
            {
                connection.disconnect();
            }
            if (in != null)
            {
                try
                {
                    in.close();
                }
                catch (IOException e)
                {
                    e.printStackTrace();
                }
            }
        }
        return result;
    }

3、post请求服务器


/**
     * <post请求服务器>
     * <功能详细描述>
     * @param url
     * @param params
     * @param encode
     * @return
     * @throws UnsupportedEncodingException
     * @see [类、类#方法、类#成员]
     */
    public static String doPost(String url,Map<String,String> params,String encode) throws UnsupportedEncodingException{
        String result = null;
        String paramsUrl = paramsToString(params, encode);
        HttpURLConnection connection = null;  
        InputStreamReader in = null;  
        try {  
            URL httpUrl = new URL(url);  
            connection = (HttpURLConnection) httpUrl.openConnection();  
            connection.setDoInput(true);  
            connection.setDoOutput(true);  
            connection.setRequestMethod("POST");  
            connection.setRequestProperty("Content-Type", "application/x-www-form-urlencoded");  
            connection.setRequestProperty("Charset", "utf-8");  
            DataOutputStream dop = new DataOutputStream(  
                    connection.getOutputStream());  
            dop.writeBytes(paramsUrl);  
            dop.flush();  
            dop.close();  
            in = new InputStreamReader(connection.getInputStream());  
            BufferedReader bufferedReader = new BufferedReader(in);  
            StringBuffer strBuffer = new StringBuffer();  
            String line = null;  
            while ((line = bufferedReader.readLine()) != null) {  
                strBuffer.append(line);  
            }  
            result = strBuffer.toString();  
        } catch (Exception e) {  
            e.printStackTrace();  
        } finally {  
            if (connection != null) {  
                connection.disconnect();  
            }  
            if (in != null) {  
                try {  
                    in.close();  
                } catch (IOException e) {  
                    e.printStackTrace();  
                }  
            }  
  
        }  
        return result;
    }


总结:在android sdk的最近的几个版本,官方是推荐使用 HttpURLConnection来实现HTTP请求。

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
好的,下面是一个简单的示例代码: ```java // 注册请求 public void register(String username, String password) { try { URL url = new URL("http://example.com/register.php"); HttpURLConnection conn = (HttpURLConnection) url.openConnection(); conn.setRequestMethod("POST"); conn.setDoOutput(true); conn.setConnectTimeout(5000); conn.setReadTimeout(5000); OutputStream os = conn.getOutputStream(); String data = "username=" + URLEncoder.encode(username, "UTF-8") + "&password=" + URLEncoder.encode(password, "UTF-8"); os.write(data.getBytes()); os.flush(); os.close(); int responseCode = conn.getResponseCode(); if (responseCode == HttpURLConnection.HTTP_OK) { // 注册成功 } else { // 注册失败 } conn.disconnect(); } catch (Exception e) { e.printStackTrace(); } } // 登录请求 public void login(String username, String password) { try { URL url = new URL("http://example.com/login.php"); HttpURLConnection conn = (HttpURLConnection) url.openConnection(); conn.setRequestMethod("POST"); conn.setDoOutput(true); conn.setConnectTimeout(5000); conn.setReadTimeout(5000); OutputStream os = conn.getOutputStream(); String data = "username=" + URLEncoder.encode(username, "UTF-8") + "&password=" + URLEncoder.encode(password, "UTF-8"); os.write(data.getBytes()); os.flush(); os.close(); int responseCode = conn.getResponseCode(); if (responseCode == HttpURLConnection.HTTP_OK) { // 登录成功 } else { // 登录失败 } conn.disconnect(); } catch (Exception e) { e.printStackTrace(); } } ``` 以上代码,register() 方法用于发送注册请求,login() 方法用于发送登录请求。其,需要替换的部分是请求的 URL 和参数,以及请求成功后的处理逻辑。注意,这里使用了 HttpURLConnection 类进行请求

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值