Android (or Java) requests data (data binding) through HttpURLConnection to Springmvc

Source: Internet
Author: User
Tags gettext

Descriptive narrative of the problem

When we use SPRINGMVC as a service-side framework, sometimes it's not just about the Web front-end (JSP, JavaScript, jquery, and so on) requests for access, and sometimes the client requests from Android and Javase (desktop apps). Therefore, in addition to the web using form forms or Ajax as the client to obtain controller responses. The pure Java language must also be implemented to provide the parameters and request results to the SPRINGMVC controller. Web front end uses form and AJAX to get controller response in this blog, the focus of this lesson is to implement pure javaclient to achieve request controller and get the response. (assuming you don't want to look at the following methods to explore, can jump directly to the third part)

Methods to explore

After identifying the issues that need to be addressed. I started searching for related blogs and questions and answers. found that the problem related to the solution is not very much, to find a lot of blog is not the correct horse mouth, but there are some to solve this problem is helpful content, and then turned a very long book, the solution to this problem has a major understanding.
The effective way to see online is to use httpclient to implement this function, just need to import httpclient and Httpcore two jar package. It was studied at the time and thought feasible.

But in the actual operation of the process. After importing the dependencies of these two jars into Android (ide:android Studio) Build.gradle, Android Studio gave two warnings when syncing, to the effect that httpclient has expired. Then I went back to a httpclient this thing and the relationship between Android, found that Android6.0 and the subsequent version number gave up the support for httpclient. It is not possible to forcibly import jar packages. (it is said that someone used a very troublesome method to import success = =) that's good. Let's not use it. Then you don't have to chant. See the reference book "Crazy Android Handout" to HttpClient also so respected. Also a little drunk.

In detail not to use the reason is no longer delve into, then study the use of httpurlconnection to solve the above problems.


In the process of using httpurlconnection, the code implementation does not have a problem with the routines. The problem is the SPRINGMVC controller how to receive data, what is the data format received? What type of data should I pass?
How does the controller receive the data? I have a general understanding of the problem of the previous period of study, SPRINGMVC Controller works is the client to the project address +controller front of the value of the URL to make a request, This request will take a few parameters. The SPRINGMVC will convert the requested number of references to the number of the controller, and then the relevant operation in this method and then return to some of the client parameters, there are several possible results of the return. Assuming that there is no @responsebody gaze, the returned data may be the name of the JSP page, then the web will jump to the corresponding JSP page assuming that Modelandview will also jump to the corresponding page and assume that adding @responsebody. Then the JSON-type data is returned, and the client receives the number of parameters returned by the controller. So, to clarify the working principle of SPRINGMVC, then how to use the HttpURLConnection to visit the controller is probably clear: we put the request address stitching good, Then send the data in the past to wait for the controller to return the data.

Then the second question comes. The requested address is clear. What should be the format of the data to be carried?
At first I thought that the same as the return value is the form of a key-value pair in JSON format, such as the user login UserName and UserPassword, (the controller is in the form of Dologin (String username,string UserPassword) I thought I should send JSON format data. But the service side does not bird me, did not obtain the participation. Later I tried again jsonarray form also not, tried the map key value pair form not. I wondered what the form was. Finally looked for half a day to see the Ajax sent the same request when the HTTP message structure to know what the data format is like.

That is true:

The middle is a & connected two parameters, the middle of the key is =, OK, finally clear. Of course this is the type of controller with two separate string values, there is a better way is to directly set the controller's parameters to one, and then parse the JSON data inside the controller, so it is actually more convenient, Later also more easy to do encryption work, just now change it too troublesome not change it. Now it's clear that the controller is a two-parameter time frame. As for the other list. Beans and JSON types are not explored here. Because I saw a lot of other bloggers talking about how to turn.

Nonsense so much. To decentralize the code.

Solve this problem

SPRINGMVC corresponding controller code (result word misspelled, too lazy to change):

@RequestMapping (value="/dologin", method=Requestmethod.POST) @ResponseBody Public Map<String, Object>Dologin (StringUserName,StringUserpassword,httpsession HttpSession) {StringResoult="Fail"; User User=UserService.GetUser (UserName); Userdetail Userdetail=Userdetailservice.Getuserdetail (UserName);if(User!=NULL){if(Objects.equals(Userdetail.Getuserdetailpassword (), UserPassword)) {httpSession.SetAttribute ("CurrentUser", user); Resoult= "Success"; }Else{Resoult= "Wrong"; }        }Else{Resoult= "Unexist"; }Map<String, Object>Resoults= NewHashMap<String, Object>(); Resoults.Put"Resoult", Resoult);returnResoults; }

A Httppostutils tool class written on the Android side or Java side

 PackageCn.justwithme.withme.Utils;ImportJava.io.BufferedReader;ImportJava.io.IOException;ImportJava.io.InputStreamReader;ImportJava.io.PrintWriter;ImportJava.net.HttpURLConnection;ImportJava.net.MalformedURLException;ImportJava.net.URL;/** * Created by Paulownia Wood on 2017/2/8. * Send HTTP requests. Get data returned by controller * * / Public classhttppostutils { Public StaticString Dopostrequest (string path,object content) {PrintWriter out=NULL; BufferedReaderinch=NULL; String Resoult ="";Try{System. out. println ("The message to be sent is:"+content);/ * Splicing url,android here needs to change the remote address, because the Android side has no way to visit localhost. Java the words of local tomcat do it anyway *String address = http://localhost:8080/withme/"+path;URL url =NewURL (address); HttpURLConnection httpurlconnection = (httpurlconnection) url.openconnection ();//These two parameters must be addedHttpurlconnection.setdoinput (true); Httpurlconnection.setdooutput (true);//Set timeout timeHttpurlconnection.setreadtimeout (Ten* +); Httpurlconnection.setconnecttimeout (Ten* +); Httpurlconnection.setrequestmethod ("POST"); Httpurlconnection.connect (); out=NewPrintWriter (Httpurlconnection.getoutputstream ());//write the parameters in the output stream             out. print (content); out. Flush ();if(Httpurlconnection.getresponsecode () = = $){inch=NewBufferedReader (NewInputStreamReader (Httpurlconnection.getinputstream (),"Utf-8")); String Line; while((line=inch. ReadLine ())! =NULL) {resoult+=line; }} System. out. println ("The result returned by the server is:"+resoult);returnResoult; }Catch(Malformedurlexception e) {System. out. println ("URL Exception");        E.printstacktrace (); }Catch(IOException e) {System. out. println ("IO exception");        E.printstacktrace (); }finally{Try{if( out!=NULL) out. Close ();if(inch!=NULL)inch. Close (); }Catch(IOException e)            {E.printstacktrace (); }        }return NULL; }}

After the tool class is written, we make some tests on both the Android and Java side, (on the premise that I have registered 14121047 on my server, you assume that it is just a test to change the server-side query database check password to a string match).
Android
Loginactivity.java

Package CN. Justwithme. WithMe. Activity;Import Android. OS. Bundle;Import Android. OS. Handler;Import Android. OS. Message;Import Android. Support. V7. App. Appcompatactivity;Import Android. View. View;Import Android. Widgets. Button;Import Android. Widgets. EditText;Importcom. Alibaba. Fastjson. JSON;Importcom. Alibaba. Fastjson. Jsonobject;Import Java. Util. HashMap;Import Java. Util. Map;Import CN. Justwithme. WithMe. R;Import CN. Justwithme. WithMe. Utils. Httppostutils;public class Loginactivity extends Appcompatactivity {private String result;Private Handler Mhanlder = new Handler () {@Override public void handlemessage (message message) { result = (String) message. obj;Jsonobject Resultjson = JSON. Parseobject(Result);String Finalresult = Resultjson. getString("Resoult");System. out. println("The result is:"+finalresult);if (Finalresult. Equals("Success")) {System. out. println("Successful Landing");} else System. out. println("username or password error");}    };@Override protected void OnCreate (Bundle savedinstancestate) {Super. OnCreate(savedinstancestate);Setcontentview (R. Layout. Activity_login);Final EditText usernameinput = (EditText) Findviewbyid (R. ID. UserName);Final EditText passwordinput = (EditText) Findviewbyid (R. ID. Password);Button login = (button) Findviewbyid (R. ID. Login);Login. Setonclicklistener(New View. Onclicklistener() {@Override public void OnClick (View v) {String userName = Usernameinput. GetText(). toString();String UserPassword = Passwordinput. GetText(). toString();Final map<string,object> userInfo = new Hashmap<string,object> ();UserInfo. Put("UserName", UserName);UserInfo. Put("UserPassword", UserPassword);Userlogin userInfo = new Userlogin ();UserInfo. Setusername(UserName);UserInfo. SetUserPassword(UserPassword);Final String user ="Username="+username+"&userpassword="+userpassword;if (username!= null &&!username. Equals("") && Userpassword!=null &&!userpassword. Equals("")){/ * Note here that the Httppostutils request cannot be placed inside the main thread in Android, and a new child thread must be created. The UI is then updated via the value of the Hanlder thread (because the child thread cannot change the UI directly) */New Thread () {public void run () {String response = Httppostutils. Dopostrequest("Dologin", user);Message message = Message. Obtain();Message. obj= Response;Mhanlder. SendMessage(message);}                    }. Start();} else{System. out. println("Username password cannot be empty");}            }        });}}

All right. This is very simple code, after all, androidclient just started to write, Activity_login.xml will not put, two input box a button just. The output can be viewed as follows to infer whether the feature is implemented:

The following is the Java test code, using the same tool class and Android.

package httpPost;publicclass test {    publicstaticvoidmain(String[] args){    "userName=14121047&userPassword=14121047";    String ans = HttpPostUtils.doPostRequest("doLogin", test);    System.out.println("server返回的数据为:"+ans);    }}

Test results are:

要发送的信息是:userName=14121047&userPassword=14121047server返回的结果是:{"resoult":"success"}server返回的数据为:{"resoult":"success"}
Conclusion

Of course, I am demonstrating the knowledge here a very simple example of Android and Java sending requests to SPRINGMVC, but since the middle of the truth and method is clear, then no matter what format data is not very difficult.

JSON data that's just a single number of parameters it's OK, two of the participants are not very easy to pass a number of parameters? It would be nice to pass the bean to the server and then turn the JSON to the bean before passing the bean. 233..

。 (Here is just a discussion about how to pass the two-number of references.) Not wanting to use JSON.


Study hard, make Progress day by day, come on!

Android (or Java) requests data (data binding) through HttpURLConnection to Springmvc

Related Article

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.