- (void)fetchOneHtmlwithUrl:(NSURL *)url withCode:(NSString *)code withValueIn:(double)valueIn withMoneyIn:(double)moneyIn
{
NSError *error;
NSData *dataGB2312 = [[NSData alloc] initWithContentsOfURL:url options:NSDataReadingMappedIfSafe error:&error];
NSStringEncoding gb2312Encoding =CFStringConvertEncodingToNSStringEncoding(kCFStringEncodingGB_18030_2000);
NSString *htmlGB2312 = [[NSString alloc] initWithData:dataGB2312 encoding:gb2312Encoding];
NSString *utf8HtmlStr = [htmlGB2312 stringByReplacingOccurrencesOfString:@"charset=gb2312"
withString:@"charset=utf-8"];
NSData *dataUTF8 = [utf8HtmlStr dataUsingEncoding:NSUTF8StringEncoding];
ParseResultBean *bean = [ParseResultBean alloc];
TFHpple *xpathParser = [[TFHpple alloc] initWithHTMLData:dataUTF8];
NSArray *eArrayCode = [xpathParser searchWithXPathQuery:@"/html/body/div[1]/div[7]/div[2]/div[1]/div[1]/div[1]/span[2]"];
TFHppleElement *eCode = [eArrayCode objectAtIndex:0];
bean->code = [[eCode attributes] objectForKey:@"title"];
[allRows addObject:bean];
}
Category Archives: Language
MAC解析JSON
NSError *parseError;
NSData *jsonData = [sJsonText dataUsingEncoding:NSUTF8StringEncoding];
NSDictionary *json = [NSJSONSerialization JSONObjectWithData:jsonData options:NSJSONReadingMutableLeaves error:&parseError];
if (json == nil)
{
NSLog(@"json parse failed. \r\n");
//NSLog([[NSString alloc] initWithData:jsonData encoding:NSUTF8StringEncoding]);
NSLog(@"%@",[parseError localizedDescription]);
return;
}
NSArray *jijinArray = [json objectForKey:@"jijinlist"];
for(NSDictionary *jijin in jijinArray)
{
NSString *sCode = [jijin objectForKey:@"code"];
NSString *sValuein = [jijin objectForKey:@"valuein"];
}
MAC系统托盘图标
- (void)viewDidLoad {
[super viewDidLoad];
// Do any additional setup after loading the view.
CGFloat f = 30.0;
statusItem = [[NSStatusBar systemStatusBar] statusItemWithLength:f];
[statusItem setHighlightMode:YES];
[statusItem setTitle:[NSString stringWithFormat:@"%@",@"Hi"]];
[statusItem setMenu:statusMenu];
[statusItem setEnabled:YES];
}
CSharp程序设置自动启动
using System;
using System.Text;
using Microsoft.Win32;
namespace GPJJ
{
class XWin32Utils
{
private const String KEY_PATH = "SOFTWARE\\MICROSOFT\\WINDOWS\\CURRENTVERSION\\RUN";
private const String VALUE_NAME = "GPJJEXE";
public static bool isAutoRun()
{
RegistryKey key = Registry.LocalMachine;
RegistryKey autorun = key.OpenSubKey(KEY_PATH, true);
Object o = autorun.GetValue(VALUE_NAME);
autorun.Close();
if(o==null)
{
return false;
}
else
{
return true;
}
}
public static void SetAutoRun(String exePath)
{
RegistryKey key = Registry.LocalMachine;
RegistryKey autorun = key.OpenSubKey(KEY_PATH, true);
autorun.SetValue(VALUE_NAME, exePath, RegistryValueKind.String);
}
public static void RemoveAutoRun()
{
if(isAutoRun())
{
RegistryKey key = Registry.LocalMachine;
RegistryKey autorun = key.OpenSubKey(KEY_PATH, true);
autorun.DeleteValue(VALUE_NAME);
}
}
}
}
Android读取并解析Json
1、不可以在UI线程直接读取网络数据,所以另起线程处理这件事情
public class MainActivity extends ActionBarActivity implements IParseJsonCallback,IParseHtmlCallback{
public void ParseJsonPage(List<PhaseResultBean> resultList) {
new ParseJson(this).execute(resultList);
}
@Override
public void ParseJsonDone(List<PhaseResultBean> resultList) {
//回调函数
}
}
2、回调接口
package com.neohope.android.gpjj;
import java.util.List;
public interface IParseJsonCallback {
void ParseJsonDone(List<PhaseResultBean> resultList);
}
3、解析Json类
package com.neohope.android.gpjj;
import android.os.AsyncTask;
import android.util.Log;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;
import java.util.ArrayList;
import java.util.List;
public class ParseJson extends AsyncTask<String,Void,List<PhaseResultBean>>{
private IParseJsonCallback jsonCallback;
public ParseJson(IParseJsonCallback jsonCallback)
{
this.jsonCallback = jsonCallback;
}
@Override
protected List<PhaseResultBean> doInBackground(String... params) {
if(params==null)return null;
List<PhaseResultBean> resultList= new ArrayList<PhaseResultBean>();
String jsonString = params[0];
try {
JSONObject json= new JSONObject(jsonString);
JSONArray jijinlist = json.getJSONArray("jijinlist");
for(int i=0;i<jijinlist.length();i++)
{
JSONObject JJ= jijinlist.getJSONObject(i);
PhaseResultBean result = new PhaseResultBean();
result.code = JJ.getString("code");
resultList.add(result);
}
} catch (JSONException e) {
e.printStackTrace();
}
return resultList;
}
@Override
protected void onPostExecute(List<PhaseResultBean> resultList) {
super.onPostExecute(resultList);
jsonCallback.ParseJsonDone(resultList);
}
@Override
protected void onPreExecute() {
super.onPreExecute();
}
}
Android用JSoup解析网页
1、不可以在UI线程直接读取网络数据,所以另起线程处理这件事情
public class MainActivity extends ActionBarActivity implements IParseJsonCallback,IParseHtmlCallback{
public void ParseHtmlPage(List<PhaseResultBean> resultList) {
new ParseHtml(this).execute(resultList);
}
@Override
public void ParseHtmlDone(List<PhaseResultBean> resultList) {
//回调函数
}
}
2、回调接口
package com.neohope.android.gpjj;
import java.util.List;
public interface IParseHtmlCallback {
void ParseHtmlDone(List<PhaseResultBean> resultList);
}
3、解析HTML类
package com.neohope.android.gpjj;
import android.os.AsyncTask;
import android.util.Log;
import org.jsoup.Jsoup;
import org.jsoup.nodes.Document;
import org.jsoup.nodes.Element;
import org.jsoup.select.Elements;
import java.io.IOException;
import java.util.List;
public class ParseHtml extends AsyncTask<List<PhaseResultBean>,Void,List<PhaseResultBean>>{
private IParseHtmlCallback htmlCallback;
public ParseHtml(IParseHtmlCallback htmlCallback)
{
this.htmlCallback = htmlCallback;
}
@Override
protected List<PhaseResultBean> doInBackground(List<PhaseResultBean>... paramList) {
if(paramList==null)return null;
List<PhaseResultBean> params = paramList[0];
for(PhaseResultBean bean : params) {
Document doc = null;
String url = bean.httpUrl;
try {
doc = Jsoup.connect(url).userAgent("Mozilla/5.0 (Windows; U; WindowsNT 5.1; en-US; rv1.8.1.6) Gecko/20070725 Firefox/2.0.0.6").timeout(5000).followRedirects(true).get();
} catch (IOException ex) {
Log.w("", ex.getMessage());
return null;
}
Document content = Jsoup.parse(doc.toString());
Element dodydiv = content.getElementById("bodydiv");
Element div = dodydiv.child(6).child(1).child(0).child(0);
Element code = div.child(0).child(2);
String szCode = code.text();
Element title = div.child(0).child(1);
String szTitle = title.text();
bean.code = szCode;
bean.name = szTitle;
}
return params;
}
@Override
protected void onPostExecute(List<PhaseResultBean> listResult) {
super.onPostExecute(listResult);
htmlCallback.ParseHtmlDone(listResult);
}
@Override
protected void onPreExecute() {
super.onPreExecute();
}
}
Android任务栏通知
private static int nId = 0;
private void RaiseSysTrayAlert(List<NEventBean> eventList)
{
NotificationManager nm = (NotificationManager) getSystemService(Context.NOTIFICATION_SERVICE);
Context context = getApplicationContext();
for(NEventBean bean : eventList)
{
Builder mBuilder = new Builder(context);
mBuilder.setTicker("XXXX");
mBuilder.setSmallIcon(R.drawable.ic_launcher);
mBuilder.setContentTitle("XXXX");
mBuilder.setContentText(bean.msg);
mBuilder.setAutoCancel(true);
Intent notifyIntent = new Intent(context, MainActivity.class);
notifyIntent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
PendingIntent pIntent = PendingIntent.getActivity(context, 0, notifyIntent, PendingIntent.FLAG_UPDATE_CURRENT);
mBuilder.setContentIntent(pIntent);
nId++;
nm.notify(nId, mBuilder.build());
}
}
Android后台服务及自动运行
1、修改AndroidManifest.xml文件
<uses-permission android:name="android.permission.RECEIVE_BOOT_COMPLETED" />
<application ...>
<service
android:name="com.neohope.android.service.NService"
android:enabled="true"
android:exported="true" >
</service>
<receiver android:name="com.neohope.android.receiver.NBroadcastReceiver">
<intent-filter>
<action android:name="android.intent.action.BOOT_COMPLETED" />
</intent-filter>
</receiver>
</application>
2、新增服务类
package com.neohope.android.service;
import android.app.Service;
import android.content.Context;
import android.content.Intent;
public class NService extends Service {
public NService() {
}
@Override
public void onCreate() {
mainThread = new WorkThread ();
mainThread.start();
}
@Override
public void onDestroy() {
mainThread.bEnd = true;
}
class WorkThread extends Thread
{
private int nInterval = 1000*60;
private boolean bEnd = false;
public JsonReaderThread()
{
}
@Override
public void run()
{
while(!bEnd)
{
DoSomething();
try {
Thread.sleep(nInterval);
} catch (InterruptedException e) {
Log.w("", "");
}
}
}
private void DoSomething()
{
}
}
3、新增广播处理类
package com.neohope.android.receiver;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import com.neohope.android.service.NService;
public class NBroadcastReceiver extends BroadcastReceiver {
@Override
public void onReceive(Context context, Intent intent) {
Intent startServiceIntent = new Intent(context, NService.class);
context.startService(startServiceIntent);
}
}
4、在Activity中添加启动代码
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
doStartService();
}
public void doStartService() {
Context context = getApplicationContext();
Intent startServiceIntent = new Intent(context, NService.class);
context.startService(startServiceIntent);
}
Android读取网页内容
1、修改AndroidManifest.xml文件
<uses-permission android:name="android.permission.INTERNET" />
2、网页读取类
package com.neohope.android.web;
import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.net.HttpURLConnection;
import java.net.MalformedURLException;
import java.net.ProtocolException;
import java.net.URL;
public class HttpUtils {
public static String readStringFromUrl(String szUrl,String szCharcode) throws IOException {
URL url = new URL(szUrl);
HttpURLConnection conn = (HttpURLConnection) url.openConnection();
conn.setConnectTimeout(5 * 1000);
conn.setRequestMethod("GET");
String szJson = "";
int resPonseCode = conn.getResponseCode();
if (conn.getResponseCode() == 200)
{
InputStream is = conn.getInputStream();
byte[] data = readStream(is);
szJson = new String(data,szCharcode);
}
return szJson;
}
private static byte[] readStream(InputStream inputStream) throws IOException {
ByteArrayOutputStream bout = new ByteArrayOutputStream();
byte[] buffer = new byte[1024];
int len = 0;
while ((len = inputStream.read(buffer)) != -1) {
bout.write(buffer, 0, len);
}
bout.close();
inputStream.close();
return bout.toByteArray();
}
}
HTML设置禁用缓存
<!-- HTTP 1.1 --> <meta http-equiv="pragma" content="no-cache"> <!-- HTTP 1.0 --> <meta http-equiv="cache-control" content="no-cache"> <!-- Prevent caching at the proxy server --> <meta http-equiv="expires" content="0">