Android HttpClient call, conflict resolution

Source: Internet
Author: User
Tags java reference

Only part of the case is applicable

Off Topic

Research Baidu automatic post for promotion failed, but login has won. Throw it all a bit wasteful.

On the basis of the login to write a Baidu automatic registration system, the function has been realized (. Net+nodejs)

With Nodejs is I did not touch clear Baidu RSA encryption algorithm, simply directly to Baidu's RSA encryption moved to NODEJS (all JS).

After the success of thinking, you can move the. NET implementation to Java, write an Android Baidu sign-in app app, practice practiced hand review Android, in passing see can make some advertising costs.

The process of moving to Java went very well, but there were several holes in the android.

. NET get token code, with Microsoft-given HttpWebRequest and Newtonsoft.json DLLs

1   Public stringGetToken (Cookiecontainer cookies) {2             stringtoken ="";3DateTime dt =DateTime.Now;4             stringtt = timeutils.convertdatetimeint (DT). ToString () +" the";5             //This step to obtain a certain failure, but mainly to get some other information Baidu. 6token = Nethelper.httpget ("https://passport.baidu.com/v2/api/?getapi&tpl=tb&apiver=v3&tt="+ TT +"&class=login&logintype=dialoglogin",refcookies);7             //This step will be successful. 8token = Nethelper.httpget ("https://passport.baidu.com/v2/api/?getapi&tpl=tb&apiver=v3&tt="+ TT +"&class=login&logintype=dialoglogin",refcookies);9Jobject Jo1 =(jobject) jsonconvert.deserializeobject (token);Ten             stringtokenstring = jo1["Data"]["token"]. ToString (); One             returntokenstring; A}

Encapsulated HTTP API

   Public Static stringHttpGet (stringUrlrefCookiecontainer Cookies) {            stringStrresult =string.            Empty; Try{HttpWebRequest Request=(HttpWebRequest) webrequest.create (URL); //request. Referer = "http://www.wangpiao.com/movie/25149/?showulcinfo=1";Request. Headers.set ("Pragma","No-cache"); Request. Cookiecontainer=cookies; HttpWebResponse Response=(HttpWebResponse) request.                GetResponse (); Stream streamreceive=Response.                GetResponseStream (); Encoding Encoding= Encoding.GetEncoding ("UTF-8"); StreamReader StreamReader=NewStreamReader (streamreceive, encoding); Strresult=Streamreader.readtoend (); Cookies. ADD (response.            Cookies); }            Catch(Exception ex) {//MessageBox.Show (ex. ToString () + "error");            }            returnstrresult; }

Move to Java reference Apache httpclient4.3.5, and Gson JSON parsing package.

 Private StaticString gettimestring () {Date now=NewDate (); returnNow.gettime () + ""; }      Public  voidGetToken ()throwsException {closeablehttpclient httpclient=Httpclients.custom (). Setdefaultcookiestore (Cookies). Build (); String TT=gettimestring (); Try{httpget HttpGet=NewHttpGet ("https://passport.baidu.com/v2/api/?getapi&tpl=tb&apiver=v3&tt=" + TT + "&class=login& Logintype=dialoglogin "); Closeablehttpresponse response1=Httpclient.execute (HttpGet); Try{response1=Httpclient.execute (HttpGet); Bytearrayinputstream bis=NewBytearrayinputstream (Entityutils.tobytearray (Response1.getentity ())); String SS=convertstreamtostring (bis). Replace ("/n", ""); Jsonparser Jsonparer=NewJsonparser ();//Initialize objects that parse JSON formattoken = jsonparer.parse (ss). Getasjsonobject (). Get ("Data"). Getasjsonobject (). Get ("token"). getasstring (); } finally{response1.close (); }           }finally{httpclient.close (); }     }  Public StaticString convertstreamtostring (InputStream is) {BufferedReader reader=NewBufferedReader (NewInputStreamReader (IS)); StringBuilder SB=NewStringBuilder (); String Line=NULL; Try {                        while(line = Reader.readline ())! =NULL) {sb.append ( line+ "/n"); }                   } Catch(IOException e) {e.printstacktrace (); } finally {                       Try{is.close (); } Catch(IOException e) {e.printstacktrace (); }                   }                   returnsb.tostring (); }   

Ok,java+nodejs has also been implemented.

Just one step, Java to Android is not very easy, and the result this step pits me for two hours

Compile first but

Run error after

The root cause is that Android comes with a httpclient package. And the referenced httpclient4.3.5 conflict.

Baidu has a way of

One: There will be used anroid (this is not crap, with Android can solve why I want to lead, Android (version 19) of the package does not support cookies, development to use)

Two: There is said to take httpclient4.3.5 source change package name re-packaging compiled, toss

Three: There are said to strip open source implementation (open source China has been grilled), since the implementation of the cookie, but the code gap missus, almost to rewrite, do not want to toss.

Four: This is from no intention to turn over, searched a reply said 4.3.3 do not conflict, by looking at the http://hc.apache.org/downloads.cgi, conflict, I do not know, but a bright, found this

HttpClient for Android 4.3.5 (GA)

This is the protagonist, filled with joy of the lead, a few turn over, OK, compiled, executed, or error

But this package is directly to the source, chase down, find a way out, the abnormal stack is the approximate impression.

Args.NotNull:item May is not NULL

Registerbuilder.register Arg.notnull

Httpclientbuilder register ("https", Sslsocketfactory)

Sslsocketfactory this thing is null.

Builder has sslsocketfactory new instance operation, chase down, found not in.

The reason is that the default value of Systemproperties is false.

Search Systemproperties found a method will set the value, call, this is finally OK.

Comparison of

Java calls

Closeablehttpclient httpclient = httpclients.custom ()                    . Setdefaultcookiestore (Cookies)                    . Build ();       

Android Fix changed to

Closeablehttpclient httpclient = httpclients.custom (). Usesystemproperties ()                    . Setdefaultcookiestore ( Cookies)                    . Build ();       

This is all OK.

Yes, Android also remember to set up Internet access

Android app Baidu Bar check-in core function has been realized.

Android HttpClient call, conflict resolution

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.