Share a practical network connection class

Source: Internet
Author: User
Tags array to string

In mobile phone development, network connections are often used to send data. Like the Web, requests on mobile phones are divided into GET requests and post requests.
The following is an httpprocess class that provides post and GET requests.

 

Package COM. thinkrace. uchome. network; import Java. io. bytearrayinputstream; import Java. io. bytearrayoutputstream; import Java. io. datainputstream; import Java. io. dataoutputstream; import Java. io. ioexception; import Java. io. inputstream; import Java. io. inputstreamreader; import Java. io. outputstream; import javax. microedition. io. connector; import javax. microedition. io. httpconnection;/***** @ author Administrator */Public class httpprocess {/*** http get request Method * This method reads the returned XML with a single character. * @ Param URL * @ return */public static string httpget (string URL) {string content = NULL; try {// open the network connection httpconnection Hc = (httpconnection) connector. open (URL); HC. setrequestmethod (httpconnection. get); inputstreamreader ISR = new inputstreamreader (HC. openinputstream (), "UTF-8"); int CH = 0; stringbuffer Buf = new stringbuffer (); While (CH = ISR. read ())! =-1) {Buf. append (char) CH);} // close the stream ISR. close (); HC. close ();} catch (ioexception ex) {system. out. println ("exception occurred in the httpget method"); Ex. printstacktrace ();} return content;}/*** GET requests with fixed memory allocation, no matter how large the returned XML is, only the portion exceeding 5 K * is truncated, the remaining items will be filled with blank space * @ Param URL * @ return */public static string httpgetbyassignmemory (string URL) {string content = NULL; try {httpconnection Hc = (httpconnection) connector. open (URL ); HC. setrequestmethod (httpconnection. get); datainputstream Dis = new datainputstream (HC. opendatainputstream (); // allocate 5 kb of memory byte [] DATA = new byte [1024*5]; DIS. read (data); content = new string (data, "UTF-8");} catch (ioexception ex) {system. out. println ("The httpgetbyallocatememory method has an exception"); Ex. printstacktrace ();} return content;} public static string httppost (string URL, string argument) {string XM L = NULL; try {httpconnection Hc = (httpconnection) connector. open (URL, connector. read_write); HC. setrequestmethod (httpconnection. post); // set post header information, useragent (set proxy), content-language (language), Content-Type (type), Content-Length (post length) HC. setrequestproperty ("User-Agent", "profile/MIDP-2.0 configuration/CLDC-1.1"); HC. setrequestproperty ("content-language", "En-us"); HC. setrequestproperty ("Content-Type "," Application/X-WWW-form-urlencoded "); byte [] postdata = argument. getbytes ("UTF-8"); HC. setrequestproperty ("Content-Length", integer. tostring (postdata! = NULL? Postdata. length: 0); outputstream out = HC. openoutputstream (); out. write (postdata); inputstream in = HC. openinputstream (); datainputstream Dis = new datainputstream (in); int CH = 0; stringbuffer Buf = new stringbuffer (); While (CH = dis. read ())! =-1) {Buf. append (char) CH);} xml = Buf. tostring ();} catch (ioexception ex) {system. out. println ("httppost method exception"); Ex. printstacktrace ();} return XML;}/*** string to a byte array * @ Param Str * @ return */public static byte [] stringtobytes (string Str) {byte [] DATA = NULL; try {bytearrayoutputstream baos = new bytearrayoutputstream (); dataoutputstream dos = new dataoutputstream (baos); dos. writeutf (STR); Data = baos. tobytearray (); baos. close (); dos. close ();} catch (exception ex) {system. out. println ("stringtobytes method exception"); Ex. printstacktrace ();} return data;}/*** byte [] array to string * @ Param data * @ return */public static string bytestostring (byte [] data) {bytearrayinputstream BAIS = new bytearrayinputstream (data); datainputstream Dis = new datainputstream (BAIS); string STR = NULL; try {STR = dis. readutf (); BAIS. close (); DIS. close ();} catch (exception ex) {system. out. println ("The bytestostring method has an exception"); Ex. printstacktrace () ;}return STR ;}}

 

Taking downloading a small image as an example, a simple HTTP connection demo is provided. Supports two different access methods: cmnet and cmwap, and filters the mobile tariff page under the cmwap access mode. Passed the test on 6120c.

Taking downloading a small image as an example, a simple HTTP connection demo is provided.
Supports two different access methods: cmnet and cmwap, and filters the mobile tariff page under the cmwap access mode.
Passed the test on 6120c.

 

Import Java. io. ioexception; import Java. io. inputstream; import javax. microedition. io. connector; import javax. microedition. io. httpconnection; import javax. microedition. lcdui. command; import javax. microedition. lcdui. commandlistener; import javax. microedition. lcdui. display; import javax. microedition. lcdui. displayable; import javax. microedition. lcdui. form; import javax. microedition. lcdui. image; import javax. MICR Oedition. lcdui. stringitem; import javax. microedition. MIDlet. MIDlet;/*** httpdemo *** @ author kf156 () **/public class httptest extends MIDlet implements commandlistener, runnable {public static final byte wait = 0; // wait for public static final byte connect = 1; // public static final byte success = 2 in the connection; // public static final byte fail = 3; // int state of failure; // display = display. getdis Play (this); Form = new form ("httptest"); Boolean cmnet = true; // whether the access point is cmnet or cmwap stringbuffer sb = new stringbuffer ("the current access mode is: cmnet \ n "); stringitem Si = new stringitem (null, sb. tostring (); command connect = new command ("networking", command. OK, 1); command change = new command ("Change Access Point Mode", command. OK, 2); command exit = new command ("exit", command. exit, 1); httpconnection HTTP; string host = "Wiki. huiho O.com "; string Path ="/images/9/9C/java.gif "; Public httptest () {state = wait; // Wait Status form. append (SI); form. addcommand (CONNECT); form. addcommand (Change); form. addcommand (exit); form. setcommandlistener (this);} protected void destroyapp (Boolean B) {} protected void pauseapp () {} protected void Startapp () {display. setcurrent (form);} public void commandaction (command C, displayable d) {If (C = = Change) {// change the Access Point if (isconnect () return; cmnet =! Cmnet; form. deleteall (); sb. Delete (0, SB. Length (); addstr ("current access method:" + (cmnet? "Cmnet": "cmwap"); form. append (SI);} else if (C = Connect) {// networking if (isconnect () return; new thread (this ). start ();} else if (C = exit) {// exit destroyapp (true); policydestroyed () ;}} public void run () {form. deleteall (); sb. delete (0, sb. length (); addstr ("current access method:" + (cmnet? "Cmnet": "cmwap"); form. append (SI); State = connect; addstr ("network connection... "); inputstream is = NULL; try {string url = NULL; url = cmnet? ("Http: //" + host + path): ("http: // 10.0.0.172: 80" + path); http = (httpconnection) connector. open (URL, connector. read_write, true); If (! Cmnet) HTTP. setrequestproperty ("X-Online-host", host); http. setrequestmethod (httpconnection. get); string contenttype = http. getheaderfield ("Content-Type"); system. out. println (contenttype); addstr (contenttype); If (contenttype! = NULL & contenttype. indexof ("text/vnd. WAP. WML ")! =-1) {// filter the mobile charges page addstr ("mobile charges page, filter! "); Http. Close (); http = NULL; http = (httpconnection) connector. Open (URL, connector. read_write, true); If (! Cmnet) HTTP. setrequestproperty ("X-Online-host", host); http. setrequestmethod (httpconnection. get); contenttype = http. getheaderfield ("Content-Type");} addstr ("Content-Type =" + contenttype); int code = http. getresponsecode (); addstr ("HTTP Code:" + code); If (code = 200) {addstr ("network connection successful, receiving data... "); is = http. openinputstream (); image = image. createimage (is); addstr ("after receiving data, show image"); form. append (Image); // receives common bytes of data // byte [] B = new byte [1024]; // int Len = 0; // bytearrayoutputstream baos = new bytearrayoutputstream (); // dataoutputstream dos = new dataoutputstream (baos); // while (LEN = is. read (B ))! =-1) {// dos. write (B, 0, Len); //} // dos. close (); // dos = NULL; // is. close (); // is = NULL; State = success; return;} else {addstr ("Page Access failed") ;}} catch (ioexception E) {addstr ("network exception:" + E. tostring (); E. printstacktrace ();} catch (exception e) {addstr ("exception:" + E. tostring (); E. printstacktrace ();} finally {If (is! = NULL) {try {is. Close () ;}catch (ioexception e) {e. printstacktrace () ;}is = NULL ;}if (HTTP! = NULL) Try {HTTP. close ();} catch (ioexception e) {e. printstacktrace ();} HTTP = NULL;} state = fail;}/*** determine whether to connect ** @ return */private Boolean isconnect () {If (State = Connect) {addstr ("network connection in progress, please wait... "); Return true;} return false;}/*** add text ** @ Param Str * The text to be added */private void addstr (string Str) {sb. append (STR + "\ n"); SI. settext (sb. tostring ());}}

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.