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;
}

相关内容