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

Source: Internet
Author: User

Problem description

When we use SPRINGMVC as a service-side framework, sometimes we need to respond not only to requests for access to the Web front-end (JSP, JavaScript, jquery, and so on), but also sometimes to requests from clients such as Android and Javase (desktop applications), so In addition to the Web using form form or Ajax as a client to obtain a controller response, the Pure Java language provides parameters and request results to the SPRINGMVC controller that must be implemented. Web front end uses form and AJAX to get controller response in this blog, the focus of this lesson is to implement a pure Java client to implement the request controller and get the response. (If you do not want to see the following method of exploration, you can jump to the third part directly)

Methods to explore

Identified the need to solve the problem, I began to search the relevant blog and question and answer, found that the problem is not a lot of solutions, find a lot of blog is irrelevant, but there are some help to solve the problem, after a long book, the solution to this problem has a basic understanding.
See online said the effective way is to use httpclient to achieve this function, but need to import httpclient and Httpcore two jar package, at that time looked at the feasibility. However, during the actual operation, after importing the dependencies of the two jar packages into Android (ide:android Studio) Build.gradle, Android Studio gave two warnings when synchronizing. The main idea is that httpclient has expired and so on, and then I specifically went to a httpclient this thing and the relationship between Android, found Android6.0 and later version of the HttpClient to abandon the support, forced import jar package is not. (it is said that some people use a very troublesome method to import success = =) that good, not to use it, then do not have to chant. See the reference book "Crazy Android Handout" to HttpClient also so respected, is a bit drunk. Specifically do not let use of the reason is no longer delve into, then study the use of httpurlconnection to solve the above problems.
In the process of using HttpURLConnection code implementation to follow the pattern of the problem is not big, 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 some parameters, and SPRINGMVC will convert the requested parameters to the controller corresponding to the value of the method under the parameters, and then in this method to carry out related operations and then return to the client some parameters, as for the return of the results there are several possibilities. If there is no @responsebody comment above, the returned data may be the name of the JSP page, then the web will jump to the corresponding JSP page if it is Modelandview will also jump to the corresponding page and if added @responsebody, Then the JSON-type data is returned, and the client receives the parameters returned by the controller. So, understand the SPRINGMVC work principle, then how to use HttpURLConnection to access 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. So the second question comes, the address of the request is clear, what format should the data carry?
At first I thought that the same as the return value is the form of a key-value pair in JSON format, such as UserName and userpassword of user login, (Controller's Parameter form is Dologin (String username,string UserPassword)) At first I thought I should send JSON format data, but the server did not bird me, did not get parameters. Later I tried again jsonarray form also not, tried the map key value pair form not. I wondered what form it 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 to two parameters, the middle of the key value is =, OK, finally understand. Of course this is the controller parameter is two separate string value when the type, there is a better way is to directly set the controller parameters to one, and then in the controller to parse the JSON data, it is actually more convenient, In the future it is easier to do encryption work, but now it is too troublesome to change it, now understand that the controller is two parameters of the time is this structure. The other List,bean and JSON types are not explored here because I see a lot of other bloggers talking about how to turn. Nonsense so much, put the code below.

Solve the 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 on 2017/2/8. * Send HTTP request for 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 does not have the way to access the Localhost,java words local tomcat runs the words.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 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 will do some testing on the Android and Java side, (in my server I have registered 14121047, if you just test the server-side query database check password changed 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("User name 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, you must create a new child thread, and then pass the value of the Hanlder thread to update the UI (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("User name password cannot be empty");}            }        });}}

Well, this is very rudimentary code, after all, the Android client has just started to write, Activity_login.xml will not put, two input box a button, you can see the output below to determine whether the function is implemented:

Here 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("服务器返回的数据为:"+ans);    }}

The test results are:

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

Of course, I'm demonstrating here a very simple example of Android and Java sending requests to SPRINGMVC, but since the middle of the truth and the method is clear, then no matter what format data is not very difficult. JSON data that only with one parameter is good, two parameters have passed a parameter is not very easy? It would be nice to pass the bean to the server and then turn the JSON to the bean before passing the bean. 233 ... (This is just a discussion of how the two parameters are passed, not the JSON.) )
Study hard, make Progress day by day, come on!

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

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.