Learn to make a simple APP from scratch

Source: Internet
Author: User

Learn to make a simple APP from scratch

I am a junior dog of information security at the Mining University. After two years of mixing up, I suddenly realized that I had decided to do what I wanted to do. The Unicom broadband of the school was charged on time and on time, however, each query has a long time and the deduction steps are very cumbersome. When I was in my sophomore year, I wanted to create an APP to help you reduce these cumbersome steps, it took more than half a year to start. It takes only one week from the beginning to the end to make the available APP. The following is the dry content. (In fact, I just want to ask for a red envelope! If you can get a red envelope, it's the first barrel of gold I earned from computer learning !)

 

First, let's take a look at the normal query steps. The first step is to log on to the online business office and enter a complicated broadband account, which is indeed troublesome.

In step 2 and later, it will be a little bit.

(Loading is slow. If there is no data in February, replace it with February .)

Then, what should I do? First, I know that web crawlers should be used. Then I know how Baidu writes a crawler using Java, and then I know that the post and get methods are used to transmit data on the server, then, use a suitable tool in the browser to capture the desired package. I learned to use firebug, a plug-in of Firefox browser. It is really a very useful tool and recommended to everyone.

As for the actual writing process, there were a lot of detours, and it was very easy to find out after the implementation. The following describes the specific implementation of Java on the computer.

First, let's talk about the basic principle. We use httpclient in an httpclient package to help us handle cookies. cookies are a general logon credential for a website. You do not need to log on again when you log on to other pages using cookies. First, we log on to the logon interface, and then visit the query page to obtain the desired data. This is the basic idea.

First, observe how data is sent to the server during login.

The meanings of several parameters are unknown. I used the same get parameter for other accounts, so we constructed a url and sent it to the server for verification.

The following is a piece of code constructed in Java code (this constructor does not appear in the org. apache package in Android, so it is easier to directly write a url .)

/**

* Login

* GenerateUriPass the get method.

*/

URIuri =NewURIBuilder ()

. SetScheme ("https ")

. SetHost ("uac.10010.com ")

. SetPath ("/portal/Service/MallLogin ")

. SetParameter ("callback", "jQuery17204165900954174946_1450622603532 ")

. SetParameter ("redirectURL", "http % 3A % 2F % 2Fwww.10010.com ")

. SetParameter ("userName", "051602198839") // User Name

. SetParameter ("password", "xxxxxx") // password

. SetParameter ("pwdType", "01 ")

. SetParameter ("productType", "04 ")

. SetParameter ("redirectType", "01 ")

. SetParameter ("areaCode", "350 ")

. SetParameter ("arrcity", "% E5 % BE % 90% E5 % B7 % 9E ")

. SetParameter ("_", "1450622609168 ")

. Build (); // generate the desired URL

HttpGethtg0 =NewHttpGet (uri );

Next, let's look at how the data we want comes from.

It is obvious that a series of post methods are returned in json format from the server's response. Among them, Flowcharts are the cost, and the totalflow duration.

There is a problem that has been difficult for a long time. Baidu finally tried a solution after a long time, that is, I directly simulate the post package to post data to the server address and did not get the desired response, the Error 500 is displayed. The final solution is as follows. We can see that psot has a lot of meaningless things in the past. I clicked on them and looked at what I did, but the fact is that we can normally return the data we want after we post the previous piece of meaningless data to the server. As for how to parse small issues such as json, Baidu is fine.

At the end of this article, we will attach the computer's Java source code. Remember to import several jar packages for running.

The next step is the magical three-day Android app. I found several Android development tutorials on the Internet, and found the chapters I needed from the directory. I only learned what I needed, so it took only three days to write this android program. In fact, it is also very simple. There is only one Activity, and the layout is dragged directly without any design. The real difficulty is the use of multithreading. In Android, network tasks cannot be processed in the main thread. The main thread can only process the UI. Therefore, Baidu has provided many examples on how to use handler, and finally implemented multi-thread writing. In addition to the most important data capturing program, the rest is to remember the password, read the details of small places such as the current date from the system, and finally write this APP and give it a try for students, finally, I uploaded it to Baidu cloud. I hope it can help more students through the posts and space.

In fact, after completing this process, I think that there are a lot of resources on the network, and there are various blogs written by the predecessors to provide you with detailed explanations and examples, what you really need to challenge is your patience. Can you calm down and make up your mind to do it well, and stick to the right path on the right path.

I didn't know httpclient at first, and tried to process cookies by myself. Downloading Android development software and environment is also a challenge, later, many problems occurred when importing the jar package during Android Development (The org. apache package), I don't know how to use the breakpoint during debugging. I tried to imitate multiple threads, but I was not able to use them after I wrote them. There are a lot of messy issues, but I can't even think of them now, I just remember that I was bored at the time, even if the network was disconnected in the middle of the night and I was driving the sdk with traffic, I did not give up. It may take 5 to 60 hours to do this, it is estimated that, except for ten hours, we were doing the right thing, and at other times we were doing useless work, but I still did it.

This is the most fulfilling thing I have ever done since I went to college. It's really a sense of accomplishment to solve a completely independent problem (well, I asked my students about Android debugging. This is a course that has been written for a long time, but I have been suffering from procrastination and haven't written it until the holiday, this time, when I saw this red packet sending activity in MOOC, I was really motivated to give a speech seriously. I hope you will be encouraged by the confused it dogs of all universities.

Appendix: import java.net. URI; import java. util. arrayList; import java. util. list; import org. apache. http. httpResponse; import org. apache. http. httpStatus; import org. apache. http. nameValuePair; import org. apache. http. client. entity. urlEncodedFormEntity; importorg. apache. http. client. methods. closeableHttpResponse; import org. apache. http. client. methods. httpGet; import org. apache. http. client. methods. httpPost; import org. apache. http. client. utils. URIBuilder; import org. apache. http. impl. client. closeableHttpClient; import org. apache. http. impl. client. httpClients; import org. apache. http. message. basicNameValuePair; import org. apache. http. util. entityUtils; import net. sf. json. JSONObject; public class HelloWorld {public static void main (String [] args) throws Exception {// TODO Auto-generated method stubCloseableHttpClienthttpclient = HttpClients. createDefault ();/*** login * to generate a uri and pass it through the get Method */URIuri = new URIBuilder (). setScheme ("https "). setHost ("uac.10010.com "). setPath ("/portal/Service/MallLogin "). setParameter ("callback", "jQuery17204165900954174946_1450622603532 "). setParameter ("redirectURL", "http % 3A % 2F % 2Fwww.10010.com "). setParameter ("userName", "051602198839") // userName. setParameter ("password", "xxxxxx") // password. setParameter ("pwdType", "01 "). setParameter ("productType", "04 "). setParameter ("redirectType", "01 "). setParameter ("areaCode", "350 "). setParameter ("arrcity", "% E5 % BE % 90% E5 % B7 % 9E "). setParameter ("_", "1450622609168 "). build (); // generate the desired URLHttpGethtg0 = new HttpGet (uri); HttpResponseresponse0 = httpclient.exe cute (htg0); System. out. println (htg0.getURI (); System. out. println (response0.getStatusLine (); Stringconfirm = EntityUtils. toString (response0.getEntity (), "UTF-8"); if (confirm. contains ("resultCode: \" 0000 \ "") System. out. println ("Login successful");/** post to the server in sequence * the preceding steps seem to have to be responded first, the cookie * is automatically generated. */HttpPostpostU = new HttpPost (); ListpostUri = new ArrayList <> (); postUri. add (" http://iservice.10010.com/e3/static/check/checklogin/?_=1450697102496 "); PostUri. add (" http://iservice.10010.com/e3/static/common/info?_=1450697103996 "); PostUri. add (" http://iservice.10010.com/e3/static/header "); PostUri. add (" http://iservice.10010.com/e3/static/query/newsAssistant/search?_=1450697104007 "); PostUri. add (" http://iservice.10010.com/e3/static/check/checklogin?_=1450697104017 "); PostUri. add (" http://iservice.10010.com/e3/static/check/checklogin?_=1450697104361 "); For (Stringpost: postUri) {URIpoU = new uribuilder(post).build(registry.postu.seturi(pou+response0#httpclient.exe cute (postU); System. out. println (response0.getStatusLine (); System. out. println ("execution completed"); Stringresult0 = EntityUtils. toString (response0.getEntity (), "UTF-8"); System. out. println (result0);} System. out. println ("prepared");/** the last post can get the desired data */HttpPosthtp = new HttpPost (" http://iservice.10010.com/e3/static/query/callFlow?_=1450697104585&menuid=000100030004 "); Listparameters = new ArrayList (); // Request body parameters. add (new BasicNameValuePair ("pageNo", "1"); parameters. add (new BasicNameValuePair ("pageSize", "20"); parameters. add (new BasicNameValuePair ("beginDate", "2015-12-01"); // parameters. add (new BasicNameValuePair ("endDate", "2015-12-25"); UrlEncodedFormEntity urlEntity = newUrlEncodedFormEntity (parameters, "UTF-8"); htp. setEntity (urlEntity); CloseableHttpResponseresponse1 implements httpclient.exe cute (htp); System. out. println (response1.getStatusLine (); String result = EntityUtils. toString (response1.getEntity (), "UTF-8"); System. out. println (result); JSONObject ob = JSONObject. fromObject (result); String totalflow = ob. get ("totalflow "). toString (); System. out. println (totalflow );}}

 

 

Appendix 2 (Android source code ):PackageCom. example. sunyang. myapplication;ImportAndroid. content. SharedPreferences;ImportAndroid. OS. Bundle;ImportAndroid. OS. Handler;ImportAndroid. OS. logoff;ImportAndroid. OS. Message;ImportAndroid. support. v7.app. AppCompatActivity;ImportAndroid. view. View;ImportAndroid. widget. Button;ImportAndroid. widget. CheckBox;ImportAndroid. widget. EditText;ImportAndroid. widget. TextView;ImportAndroid. widget. Toast;ImportOrg. apache. http. HttpResponse;ImportOrg. apache. http. NameValuePair;ImportOrg. apache. http. client. ClientProtocolException;ImportOrg. apache. http. client. HttpClient;ImportOrg. apache. http. client. entity. UrlEncodedFormEntity;ImportOrg. apache. http. client. methods. HttpGet;ImportOrg. apache. http. client. methods. HttpPost;ImportOrg. apache. http. impl. client. DefaultHttpClient;ImportOrg. apache. http. message. BasicNameValuePair;ImportOrg. apache. http. util. EntityUtils;ImportOrg. json. JSONArray;ImportOrg. json. JSONObject;ImportJava. io. IOException;ImportJava. io. UnsupportedEncodingException;ImportJava.net. MulticastSocket;ImportJava. text. SimpleDateFormat;ImportJava. util. ArrayList;ImportJava. util. Date;ImportJava. util. List;Public classMainActivityExtendsAppCompatActivity {TextViewRes; HttpClientHttpClient; SharedPreferencesPreferences; SharedPreferences. EditorEditor;/* Construct handler in the main thread, and send the UI update request using sendMessage .*/HandlerHandler=NewHandler (){Public voidHandleMessage (Message msg ){If(Msg.What= 0x123 ){Res. Append (msg.Obj. ToString () +"\ N");}}};Public voidOnCreate (Bundle savedInstanceState ){Super. OnCreate (savedInstanceState); setContentView (R. layout.Activity_main);HttpClient=NewDefaultHttpClient ();Preferences= GetSharedPreferences ("UserInfo",MODE_WORLD_READABLE);Editor=Preferences. Edit ();Res= (TextView) findViewById (R. id.Result); Button bn = (Button) findViewById (R. id.Button);FinalEditText username = (EditText) findViewById (R. id.UserName);FinalEditText password = (EditText) findViewById (R. id.Password);FinalCheckBox checkBox = (CheckBox) findViewById (R. id.CheckBox);If(Preferences. GetBoolean ("AUTO_ISCHECK",True) {Username. setText (Preferences. GetString ("UserName",""); Password. setText (Preferences. GetString ("Password","");} Bn. setOnClickListener (NewView. OnClickListener () {@ OverridePublic voidOnClick (View v ){FinalString name = username. getText (). toString ();FinalString pwd = password. getText (). toString ();If(CheckBox. isChecked ()){Editor. PutString ("UserName", Name );Editor. PutString ("Password", Pwd );Editor. PutBoolean ("AUTO_ISCHECK",True). Commit ();// Store the username and password in the xml file}Else editor. PutBoolean ("AUTO_ISCHECK",False). Commit ();NewThread (){/* Threads used for the Network */Public voidRun (){Try{/* The login code */String url ="Https://uac.10010.com/portal/Service/MallLogin? Callback = jQuery17204165900954174946_1450622603532 & redirectURL = http % 253A % 252F % 252Fwww.10010.com"+"& UserName ="+ Name +"& Password ="+ Pwd +"& PwdType = 01 & productType = 04 & redirectType = 01 & areaCode = 350 & arrcity = % 25E5% 25BE % 2590% 25E5% 25B7% 259E & _ = 1450622609168"; HttpGet =NewHttpGet (url); HttpResponse response =HttpClient. Execute (get); String confirm = EntityUtils.ToString(Response. getEntity (),"UTF-8"); Message msg =NewMessage (); msg.What= 0x123;If(Confirm. contains ("ResultCode: \" 0000 \"") {Msg.Obj="Login successful";Handler. SendMessage (msg );}Else{Msg.Obj="Incorrect user name or password";Handler. SendMessage (msg );}/* Code for sending the post Request */List
 
  
PostUri =
  NewArrayList <> (); postUri. add (
  "Http://iservice.10010.com/e3/static/check/checklogin? = 1450697102496"); PostUri. add (
  "Http://iservice.10010.com/e3/static/common/info? = 1450697103996"); PostUri. add (
  Http://iservice.10010.com/e3/static/header"); PostUri. add (
  "Http://iservice.10010.com/e3/static/query/newsAssistant/search? = 1450697104007"); PostUri. add (
  "Http://iservice.10010.com/e3/static/check/checklogin? = 1450697104017"); PostUri. add (
  "Http://iservice.10010.com/e3/static/check/checklogin? = 1450697104361");
  For(String post: postUri) {HttpPost postU =
  NewHttpPost (post); HttpResponse response0 =
  HttpClient. Execute (postU);} Message msg1 =
  NewMessage (); msg1.
  What= 0x123; msg1.
  Obj=
  "Send request";
  Handler. SendMessage (msg1); SimpleDateFormat sdf =
  NewSimpleDateFormat (
  "Yyyy-MM-dd"); SimpleDateFormat sdf1 =
  NewSimpleDateFormat (
  "Yyyy-MM"); String endDate = sdf. format (
  NewDate (); String beginDate = sdf1.format (
  NewDate () +
  "-01"; Message msg2 =
  NewMessage (); msg2.
  What= 0x123; msg2.
  Obj=
  "Start Date :"+ BeginDate +
  "\ T deadline :"+ EndDate;
  Handler. SendMessage (msg2); HttpPost htp =
  NewHttpPost (
  "Http://iservice.10010.com/e3/static/query/callFlow? _ = 1450697104585 & menuid = 000100030004"); List
  
   
Parameters =
   NewArrayList
   
    
();
    // Request bodyParameters. add (
    NewBasicNameValuePair (
    "PageNo",
    "1"); Parameters. add (
    NewBasicNameValuePair (
    "PageSize",
    "20"); Parameters. add (
    NewBasicNameValuePair (
    "BeginDate", BeginDate); parameters. add (
    NewBasicNameValuePair (
    "EndDate", EndDate); UrlEncodedFormEntity urlEntity =
    NewUrlEncodedFormEntity (parameters,
    UTF-8"); Htp. setEntity (urlEntity); HttpResponse result =
    HttpClient. Execute (htp); String s = EntityUtils.
    ToString(Result. getEntity (),
    "UTF-8");
    // Processing resultJSONObject ob =
    NewJSONObject (s); String totalflow = ob. get (
    "Totalflow"). ToString (); String response = ob. get (
    "Flowcharts"). ToString ();
    IntTotal = Integer.
    ParseInt(Totalflow)/3600; Message msg3 =
    NewMessage (); msg3.
    What= 0x123; msg3.
    Obj=
    "Total duration :"+ Totalflow +
    "Seconds \ n"+
    "Approximately"+ Total +
    "Hour \ n"+
    "Total fee :"+ Response;
    Handler. SendMessage (msg3 );}
    Catch(Exception e) {e. printStackTrace () ;}}. start ();}});}}
   
  
 

 

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.