As a result of the recent online search for a lot of Android connection to the HTTP method, but 2013 years ago, the method can not be used now, or error, or abandoned, the years left behind the things can only be sorted by themselves.
It's really simple, just a httputil generic class. Can implement get and post method, other things, inside can be arbitrarily changed, basically so.
parameter, I used a strurlpath URL, params key-value pair, encode code (such as Utf-8).
Package Utilimport Android.os.Handlerimport Android.os.Messageimport android.view.Viewimport Android.widget.Buttonimport Java.io.BufferedReaderimport Java.io.ByteArrayOutputStreamimport Java.io.IOExceptionimport Java.io.InputStreamimport Java.io.InputStreamReaderimport Java.io.OutputStreamimport Java.net.HttpURLConnectionimport java.net.MalformedURLExceptionimport Java.net.URLimport java.net.urlencoder/** * Created by Jason_jan on 2017/7/5. */object Httputil {private var handler:handler? = null private var my_result:string? = null fun HttpGet (strURL Path:string, Params:map<string, String>, encode:string): String {var strurlpath = strurlpath/* by te[] data = Getrequestdata (params, encode). ToString (). GetBytes ();//Get Request body */* String target= "http://emb.mobi/regist ER "; */var result:string? = null val append_url = Getrequestdata (params, encode). toString () Strurlpath = Strurlpath + "?" + Append_url try {Val URL= URL (Strurlpath) Val urlconn = Url.openconnection () as HttpURLConnection urlconn.connecttimeout = 5 000//Timeout Time Urlconn.setrequestproperty ("Content-type", "application/x-www-form-urlencoded")//Set header information, actually no use The protagonist starts to debut, not paying attention to just a few hours of debugging, input stream val ' in ' = InputStreamReader (urlconn.inputstream) val buffer = buffer Edreader (' in ') var inputline:string? = NULL//loop reads the contents of the input stream by line result = ""//each time the data is emptied while (buffer.readline (). apply {Inputline = t his} = null) {result + = inputline!! + "\ n"} ' in '. Close () Urlconn.disco Nnect ()} catch (E:malformedurlexception) {e.printstacktrace ()} catch (Ioe:ioexception) { Ioe.printstacktrace () return "ERR:" + ioe.message.toString ()} return result!!} Private Fun Getrequestdata (params:map<string, String>, encode:string): stringbuffer { Val StringBuffer = StringBuffer ()//Store packaged request body information try {for (key, value) in params) { Stringbuffer.append (Key). Append ("="). Append (Urlencoder.encode (value, encode)). Append ("&")} Stringbuffer.deletecharat (stringbuffer.length-1 )//delete the Last "&"} catch (E:exception) {e.printstacktrace ()} return StringBuffer } Fun HttpPost (strurlpath:string, params:map<string, String>, encode:string): String {val data = Get RequestData (params, encode). ToString (). Tobytearray () try {val url = url (strurlpath) Val http = Url.openconnection () as httpurlconnection http.connecttimeout = Http.doinput = True Http.dooutput = True Http.requestmethod = "post" http.usecaches = false//cannot be cached using post Set the type of the request body is the text type Http.setrequestproperty ("Content-type", "application/x-www-form-urlencoded")//Set the length of the request body Http.set Requestproperty ("Content-length", data.size.toString ())//Get output stream, write data to server val out = Http.outputstream Out.write (data) val response = Http.responsecode if (response = = Httpurlconnection.http_ OK) {val InputStream = http.inputstream return Dealresponseresult (InputStream)} } catch (Ioe:ioexception) {ioe.printstacktrace () return "ERR:" + ioe.message.toString () } return "-1"} Fun Dealresponseresult (Inputstream:inputstream): String {var resultdata:string ? = NULL//Storage processing result val Bytearrayoutputstream = Bytearrayoutputstream () val data = ByteArray (1024x768) v Ar len = 0 try {inputstream.read (data). apply {len = this}! =-1) {Bytearrayout Putstream.write (data,0, Len)}} catch (E:ioexception) {e.printstacktrace ()} Resultdata = String ( Bytearrayoutputstream.tobytearray ()) Return Resultdata}}
The way to use it is simple--httputil. The method name (parameter), returns a string, and then resolves it with the JSON parsing tool.
The second most serious, Android network connection A bit of a pit. Here are two things to talk about.
1.getoutputstream here, has been an error. Solution: Build.gradle
Compile ' com.squareup.retrofit:retrofit:1.8.0 ' compile ' com.squareup.okhttp:okhttp:2.1.0 ' compile ' com.squareup.okhttp:okhttp-urlconnection:2.1.0 '
2. Second, in the Androidmanifest.xml
<uses-permission android:name= "Android.permission.ACCESS_WIFI_STATE"/><uses-permission android:name= " Android.permission.ACCESS_NETWORK_STATE "/><uses-permission android:name=" Android.permission.INTERNET "/ >
Android Kotlin Connect http