关于android:AndroidHttpURLConnection接口

3次阅读

共计 5261 个字符,预计需要花费 14 分钟才能阅读完成。

Android 中提供的 HttpURLConnection 和 HttpClient 接口能够用来开发 HTTP 程序。

  1. HttpURLConnection 接口
        首先须要明确的是,Http 通信中的 POST 和 GET 申请形式的不同。GET 能够取得动态页面,也能够把参数放在 URL 字符串前面,传递给服务器。而 POST 办法的参数是放在 Http 申请中。因而,在编程之前,该当首先明确应用的申请办法,而后再依据所应用的形式抉择相应的编程形式。
        HttpURLConnection 是继承于 URLConnection 类,二者都是抽象类。其对象次要通过 URL 的 openConnection 办法取得。创立办法如下代码所示:

    URL url = new URL("http://www.51cto.com/index.jsp?par=123456");  
    HttpURLConnection urlConn=(HttpURLConnection)url.openConnection(); 

       
    通过以下办法能够对申请的属性进行一些设置,如下所示:

 
 

// 设置输出和输入流  
urlConn.setDoOutput(true);  
urlConn.setDoInput(true);  
// 设置申请形式为 POST  
urlConn.setRequestMethod("POST");  
//POST 申请不能应用缓存  
urlConn.setUseCaches(false);  
// 敞开连贯  
urlConn.disConnection();  

HttpURLConnection 默认应用 GET 形式,例如上面代码所示:
 
 

// 应用 HttpURLConnection 关上连贯  
                HttpURLConnection urlConn = (HttpURLConnection) url.openConnection();  
                // 失去读取的内容 (流)  
                InputStreamReader in = new InputStreamReader(urlConn.getInputStream());  
                // 为输入创立 BufferedReader  
                BufferedReader buffer = new BufferedReader(in);  
                String inputLine = null;  
                // 应用循环来读取取得的数据  
                while (((inputLine = buffer.readLine()) != null))  
                {  
                    // 咱们在每一行前面加上一个 "\n" 来换行  
                    resultData += inputLine + "\n";  
                }           
                // 敞开 InputStreamReader  
                in.close();  
                // 敞开 http 连贯  
                urlConn.disconnect(); 

如果须要应用 POST 形式,则须要 setRequestMethod 设置。代码如下:
 
 

String httpUrl = "http://192.168.1.110:8080/httpget.jsp";  
        // 取得的数据  
        String resultData = "";  
        URL url = null;  
        try 
        {  
            // 结构一个 URL 对象  
            url = new URL(httpUrl);   
        }  
        catch (MalformedURLException e)  
        {Log.e(DEBUG_TAG, "MalformedURLException");  
        }  
        if (url != null)  
        {  
            try 
            {  
                // 应用 HttpURLConnection 关上连贯  
                HttpURLConnection urlConn = (HttpURLConnection) url.openConnection();  
                // 因为这个是 post 申请, 设立须要设置为 true  
                urlConn.setDoOutput(true);  
                urlConn.setDoInput(true);  
                // 设置以 POST 形式  
                urlConn.setRequestMethod("POST");  
                // Post 申请不能应用缓存  
                urlConn.setUseCaches(false);  
                urlConn.setInstanceFollowRedirects(true);  
                // 配置本次连贯的 Content-type,配置为 application/x-www-form-urlencoded 的  
                urlConn.setRequestProperty("Content-Type","application/x-www-form-urlencoded");  
                // 连贯,从 postUrl.openConnection() 至此的配置必须要在 connect 之前实现,// 要留神的是 connection.getOutputStream 会隐含的进行 connect。urlConn.connect();  
                //DataOutputStream 流  
                DataOutputStream out = new DataOutputStream(urlConn.getOutputStream());  
                // 要上传的参数  
                String content = "par=" + URLEncoder.encode("ABCDEFG", "gb2312");  
                // 将要上传的内容写入流中  
                out.writeBytes(content);   
                // 刷新、敞开  
                out.flush();  
                out.close();  
  1. HttpClient 接口
        应用 Apache 提供的 HttpClient 接口同样能够进行 HTTP 操作。
        对于 GET 和 POST 申请办法的操作有所不同。GET 办法的操作代码示例如下:
     
     

    // http 地址  
            String httpUrl = "http://192.168.1.110:8080/httpget.jsp?par=HttpClient_android_Get";  
            //HttpGet 连贯对象  
            HttpGet httpRequest = new HttpGet(httpUrl);  
             // 获得 HttpClient 对象  
                HttpClient httpclient = new DefaultHttpClient();  
                // 申请 HttpClient,获得 HttpResponse  
                HttpResponse httpResponse = httpclient.execute(httpRequest);  
                // 申请胜利  
                if (httpResponse.getStatusLine().getStatusCode() == HttpStatus.SC_OK)  
                {  
                    // 获得返回的字符串  
                    String strResult = EntityUtils.toString(httpResponse.getEntity());  
                    mTextView.setText(strResult);  
                }  
                else 
                {mTextView.setText("申请谬误!");  
                }  
            } 
    

    应用 POST 办法进行参数传递时,须要应用 NameValuePair 来保留要传递的参数。,另外,还须要设置所应用的字符集。代码如下所示:
     

 


// http 地址  
        String httpUrl = "http://192.168.1.110:8080/httpget.jsp";  
        //HttpPost 连贯对象  
        HttpPost httpRequest = new HttpPost(httpUrl);  
        // 应用 NameValuePair 来保留要传递的 Post 参数  
        List<NameValuePair> params = new ArrayList<NameValuePair>();  
        // 增加要传递的参数  
        params.add(new BasicNameValuePair("par", "HttpClient_android_Post"));  
        // 设置字符集  
            HttpEntity httpentity = new UrlEncodedFormEntity(params, "gb2312");  
            // 申请 httpRequest  
            httpRequest.setEntity(httpentity);  
            // 获得默认的 HttpClient  
            HttpClient httpclient = new DefaultHttpClient();  
            // 获得 HttpResponse  
            HttpResponse httpResponse = httpclient.execute(httpRequest);  
            //HttpStatus.SC_OK 示意连贯胜利  
            if (httpResponse.getStatusLine().getStatusCode() == HttpStatus.SC_OK)  
            {  
                // 获得返回的字符串  
                String strResult = EntityUtils.toString(httpResponse.getEntity());  
                mTextView.setText(strResult);  
            }  
            else 
            {mTextView.setText("申请谬误!");  
            }  
        } 

HttpClient 实际上是对 Java 提供办法的一些封装,在 HttpURLConnection 中的输入输出流操作,在这个接口中被对立封装成了 HttpPost(HttpGet) 和 HttpResponse,这样,就缩小了操作的繁琐性。
另外,在应用 POST 形式进行传输时,须要进行字符编码。

正文完
 0