閱讀904 返回首頁    go 阿裏雲 go 技術社區[雲棲]


J2ME通過URL訪問XML文件並下載XML到本地

(葉全府)J2ME通過URL訪問XML文件並下載XML到本地
2009-06-11 14:45
**
     * 網絡連接
     * 固定URL的網絡連接
     *
@param cmnet
     *            true走cmnet false走cmwap
     *
@return返回String類型的XML數據
    
*/
   
private String connect(boolean cmnet) {

       
try {
           
if (cmnet) {

                http
= (HttpConnection) Connector
                        .open(
https://xx.cn/t.xml);

            }
else {
                http
= (HttpConnection) Connector
                        .open(
https://10.0.0.3/t.xml);
                http.setRequestProperty(
"X-Online-Host", "xx.cn");
            }

            http.setRequestProperty(
"Content-Type", "application/octet-stream");
            http.setRequestProperty(
"Connection", "Keep-Alive");
            http.setRequestMethod(HttpConnection.GET);

           
// 判斷是否為連接網絡收費提示頁麵
            String content_type = http.getHeaderField("Content-Type");
           
// 如果是返回移動的攔截頁麵,則重發.
            if (content_type.indexOf("wml") != -1) {
               
try {
                    http.close();
                }
catch (IOException e) {
                }
                http
= null;
               
// 重新發起一次請求

               
if (cmnet) {
                    http
= (HttpConnection) Connector
                            .open(
https://xx.cn/t.xml);
                }
else {
                    http
= (HttpConnection) Connector
                            .open(
https://10.0.0.3/t.xml);
                    http.setRequestProperty(
"X-Online-Host",
                           
"xx.cn");
                }
                http.setRequestMethod(HttpConnection.GET);

            }
           
int code = http.getResponseCode();

           
if (code == 200) {// 返回200 表示連接成功

               
// 打開輸入流,讀取數據
                InputStreamReader is = new InputStreamReader(http
                        .openInputStream(),
"UTF-8");
               
// 建一StringBuffer,用於保存已讀的數據
                StringBuffer sb = new StringBuffer();
               
// 每次讀取1K的數據
                char[] c = new char[1024];
               
int k;
               
// 循環讀取數據,直到讀完 當返回-1時表示流已讀完
                while ((k = is.read(c)) != -1) {
                    sb.append(c,
0, k);
                }

                is.close();
                is
= null;
                http.close();
                http
= null;
               
return sb.toString();
            }
        }
catch (Exception e) {
            e.printStackTrace();
           
// return null;
        } finally {

           
if (http != null) {
               
try {
                    http.close();
                    http
= null;
                }
catch (IOException e) {
                }
                http
= null;
            }
        }

       
return null;
    }

最後更新:2017-04-02 06:51:20

  上一篇:go (轉載)Histograms of Oriented Gradients (HOG)理解
  下一篇:go [原創]NT係統信息察看工具 : NtInfoGuy