歡迎來到Linux教程網
Linux教程網
Linux教程網
Linux教程網
您现在的位置: Linux教程網 >> UnixLinux >  >> Linux編程 >> Linux編程

Android 網絡連接 打開 Url下載 信息

1. 簡單版本

java代碼:

/**
* 根據URL下載文件,前提是這個文件當中的內容是文本,函數的返回值就是文件當中的內容 1.創建一個URL對象
* 2.通過URL對象,創建一個HttpURLConnection對象 3.得到InputStram 4.從InputStream當中讀取數據
*
* @param urlStr
* @return
*/
public String getTextFromUrl(String urlStr) {
StringBuffer sb = new StringBuffer();
String line = null;
BufferedReader buffer = null;
try {
// 創建一個URL對象
url = new URL(urlStr);
// 創建一個Http連接
HttpURLConnection urlConn = (HttpURLConnection) url
.openConnection();
// 使用IO流讀取數據
buffer = new BufferedReader(new InputStreamReader(
urlConn.getInputStream()));
while ((line = buffer.readLine()) != null) {
sb.append(line);
}
} catch (Exception e) {
e.printStackTrace();
} finally {
try {
buffer.close();
} catch (Exception e) {
e.printStackTrace();
}
}
return sb.toString();
}


2. 發送http信息,並信息進行編碼


java代碼:

//發送http信息,並信息進行編碼
public String SendDataPost(String url, String post)
{
// 判斷網絡鏈接是否正常
if (isNetworkAvailable(fromcon)) {
try
{
String mString = new String(post.getBytes(), “UTF-8″);
URL iurl = new URL(url);//直接提交地址,不要帶參數
HttpURLConnection objConn = (HttpURLConnection)iurl.openConnection();
//objConn.setRequestProperty(“Cookie”,HttpTools.PublishCookies());
objConn.setDoOutput(true);
objConn.setDoInput(true);
objConn.setRequestProperty(“Content-type”,”application/x-www-form-urlencoded”);
objConn.setRequestMethod(“POST”);
objConn.setRequestProperty(“Content-Length”,String.valueOf(mString.toCharArray().length));
objConn.setConnectTimeout(30000);
objConn.setReadTimeout(30000);
objConn.connect();
OutputStream objSM = objConn.getOutputStream();
OutputStreamWriter objSW = new OutputStreamWriter(objSM);
BufferedWriter out = new BufferedWriter(objSW);
out.write(mString.toCharArray(),0,mString.toCharArray().length);
out.flush();
out.close();
InputStream objSMP = objConn.getInputStream();
InputStreamReader objSRP = new InputStreamReader(objSMP, “utf-8″);
BufferedReader in = new BufferedReader(objSRP);
String line = null;
StringBuilder sb = new StringBuilder();
while ((line = in.readLine()) != null) {
sb.append(line);
}
in.close();
String resp = sb.toString();
objSMP.close();
objConn.disconnect();
return resp;
}catch (Exception ex) {
Log.i(“CCCC”, ex.toString());
return “”;
}
}else{
Intent intent0 = new Intent(fromcon,LoginActivity.class);
intent0.putExtra(“msg”,“您當前網絡連接已禁用,請重新設置!”);
fromcon.startActivity(intent0);
return “”;
}
}
// 判斷網絡是否正常
public static boolean isNetworkAvailable(Context context) {
ConnectivityManager connectivity = (ConnectivityManager) context.getSystemService(Context.CONNECTIVITY_SERVICE);
if (connectivity == null) {
return false;
} else {
NetworkInfo info = connectivity.getActiveNetworkInfo();
if (info == null) {
return false;
} else {
if (info.isAvailable()) {
return true;
}
}
}
return false;
}
Copyright © Linux教程網 All Rights Reserved