16.Http获取数据
(1)Get 方式1:
String httpUrl = "";
//获得的数据
String resultData = "";
//构造一个URL对象
URL url = new URL(httpUrl);
// 使用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();
Get方式2:
// http地址
String httpUrl = "";
//HttpGet连接对象
HttpGet httpRequest = new HttpGet(httpUrl);
try
{
//取得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("请求错误!");
}
}
catch (ClientProtocolException e)
{
mTextView.setText(e.getMessage().toString());
}
catch (IOException e)
{
mTextView.setText(e.getMessage().toString());
}
catch (Exception e)
{
mTextView.setText(e.getMessage().toString());
}
(2)POST方式1:
// 使用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();
//获取数据
BufferedReader reader = new BufferedReader(new InputStreamReader(urlConn.getInputStream()));
String inputLine = null;
//使用循环来读取获得的数据
while (((inputLine = reader.readLine()) != null))
{
//我们在每一行后面加上一个"\n"来换行
resultData += inputLine + "\n";
}
reader.close();
//关闭http连接
urlConn.disconnect();
Post方式2:
// http地址
String httpUrl = "";
//HttpPost连接对象
HttpPost httpRequest = new HttpPost(httpUrl);
//使用NameValuePair来保存要传递的Post参数
List params = new ArrayList();
//添加要传递的参数
params.add(new BasicNameValuePair("par", "HttpClient_android_Post"));
try
{
//设置字符集
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("请求错误!");
}
}
catch (ClientProtocolException e)
{
mTextView.setText(e.getMessage().toString());
}
catch (IOException e)
{
mTextView.setText(e.getMessage().toString());
}
catch (Exception e)
{
mTextView.setText(e.getMessage().toString());
}
(3)直接获取
//使用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();
17.使用webview加载网页
//设置支持JavaScript脚本
WebSettings webSettings = mWebView.getSettings();
webSettings.setJavaScriptEnabled(true);
//设置可以访问文件
webSettings.setAllowFileAccess(true);
//设置支持缩放
webSettings.setBuiltInZoomControls(true);
//设置WebChromeClient
mWebView.setWebChromeClient(new WebChromeClient(){
@Override
//处理javascript中的alert
public boolean onJsAlert(WebView view, String url, String message,
final JsResult result)
{
//可以构建一个Builder来显示网页中的对话框,来提示消息
return true;
};
@Override
//处理javascript中的confirm
public boolean onJsConfirm(WebView view, String url, String message,
final JsResult result)
{
//可以构建一个带选择的对话框,来提示消息
return true;
};
@Override
//处理javascript中的prompt
//message为网页中对话框的提示内容
//defaultValue在没有输入时,默认显示的内容
public boolean onJsPrompt(WebView view, String url, String message,
String defaultValue, final JsPromptResult result) {
//自定义一个带输入的对话框由TextView和EditText构成
final LayoutInflater factory = LayoutInflater.from(Activity01.this);
final View dialogview = factory.inflate(R.layout.prom_dialog, null);
//设置TextView对应网页中的提示信息
((TextView) dialogview.findViewById(R.id.TextView_PROM)).setText(message);
//设置EditText对应网页中的输入框
((EditText) dialogview.findViewById(R.id.EditText_PROM)).setText(defaultValue);
Builder builder = new Builder(Activity01.this);
builder.setTitle("带输入的对话框");
builder.setView(dialogview);
builder.setPositiveButton(android.R.string.ok,
new AlertDialog.OnClickListener() {
public void onClick(DialogInterface dialog, int which) {
//点击确定之后,取得输入的值,传给网页处理
String value = ((EditText) dialogview.findViewById(R.id.EditText_PROM)).getText().toString();
result.confirm(value);
}
});
builder.setNegativeButton(android.R.string.cancel,
new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int which) {
result.cancel();
}
});
builder.setOnCancelListener(new DialogInterface.OnCancelListener() {
public void onCancel(DialogInterface dialog) {
result.cancel();
}
});
builder.show();
return true;
};
//判断输入的内容是不是网址
if ( URLUtil.isNetworkUrl(url) )
{
//装载网址
mWebView.loadUrl(url);
}
//返回前一个页面
if (mWebView.canGoBack())
{
mWebView.goBack();
}
18.Intent传输数据
//生成一个Intent对象
Intent intent = new Intent();
//在Intent对象当中添加键值对
intent.putExtra("one","FirstStr");
intent.putExtra("two","SecondStr);
也可以写成如下,两种方法等价,获取方式也可以通用:
Bundle b=new Bundle();
b.putString("one","FirstStr");
b.putString("one","FirstStr");
intent.putExtra(b);
//设置Intent对象要启动的Activity
intent.setClass(Activity01.this, Activity02.class);
Activity中取数据
//取得从上一个Activity当中传递过来的Intent对象
Intent intent = getIntent();
//从Intent当中根据key取得value
String value = intent.getStringExtra("one");
或者使用:
Bundle b=intent.getExtra();
String value = b.getString("one");
//启动发送短信的Activity
Uri uri = Uri.parse("smsto://0800000123");
Intent intent = new Intent(Intent.ACTION_SENDTO, uri);
intent.putExtra("sms_body", "The SMS text");
startActivity(intent);
19.wifi管理
//取得WifiManager对象
mWifiManager = (WifiManager) context.getSystemService(Context.WIFI_SERVICE);
//取得WifiInfo对象
mWifiInfo = mWifiManager.getConnectionInfo();
//打开WIFI
mWifiManager.setWifiEnabled(true);
//关闭WIFI
mWifiManager.setWifiEnabled(false);
//锁定WifiLock
mWifiLock.acquire();
//判断时候锁定
if (mWifiLock.isHeld())
{
//解锁WifiLock
mWifiLock.acquire();
}
//创建一个WifiLock
mWifiLock = mWifiManager.createWifiLock("Test");
//连接配置好的指定ID的网络
mWifiManager.enableNetwork(mWifiConfiguration.get(index).networkId, true);
//添加一个网络并连接
public void AddNetwork(WifiConfiguration wcg)
{
int wcgID = mWifiManager.addNetwork(wcg);
mWifiManager.enableNetwork(wcgID, true);
}
//断开指定ID的网络
mWifiManager.disableNetwork(networkId);
mWifiManager.disconnect();
//开始扫描
mWifiManager.startScan();
//得到扫描结果
mWifiList = mWifiManager.getScanResults();
//得到配置好的网络连接
mWifiConfiguration = mWifiManager.getConfiguredNetworks();
20.Android 中的ListView内容刷新问题
我在处理adpter数据的时候,由于数据变化,需要刷新view,但是invalidate()方法无效,于是Adapter.notifyDataSetChanged();成功
同时还尝试了一下重新setAdapter 然后invalidate();也成功了,不过有网友说尝试后一种方法失败
阅读(1455) | 评论(0) | 转发(0) |