The road to Java development 2016.12.26

Source: Internet
Author: User

I first entered the doorway. Code slightly rough, welcome to correct!

Recently in the company's project, need to and other companies to do business docking, the other side directly thrown over a protocol for development, recently looked a little bit, wrote a protocol to obtain data through the method

The contents of the other party's agreement are as follows:

According to the content of the protocol can be HTTP to obtain the corresponding business data, but the parameters sent and the returned data are in JSON format, encoded in accordance with the UTF-8 format

Thus wrote the following short paragraph of content

Privatebackdata getdatafromdh (String method,string param) {URL url=NULL;
Custom entity classes, I customize the type of JSON corresponding to the return of the other backdata data
=NULL; Try {
Here the parameters BaseURL, method, param synthesize a complete URL such as http://192.168.29.200:8080/dahuaIS/rest/statistic/picrecord/parameter
Here's the parameter param in the following article will be specifically explained
URL
=NewURL ("http.//" +baseurl+method+param); HttpURLConnection Connection=(HttpURLConnection) url.openconnection ();//Get connection
The Set method here mainly sets the parameters of some request headers Connection.setrequestmethod (
"GET");//Set Request mode Connection.setrequestproperty ("Accept", "Application/json"); Connection.setrequestproperty ("Content-type", "Application/json"); Connection.setrequestproperty ("Authorization", authorization);//According to the requirements set by the other relevant certification content connection.connect (); Gson Gson=NewGsonbuilder (). Create ();//Using Google's Gson.jar here can easily turn objects and JSON formats InputStream is=Connection.getinputstream (); InputStreamReader R=NewInputStreamReader (IS, "Utf-8"); BufferedReader BR=NewBufferedReader (R); String s=br.readline ();//lazy here to read a complete string directly, because the returned JSON is actually a complete line string data= Gson.fromjson (S, Backdata.class);
Finally close the flow br.close (); R.close (); Is.close (); Connection.disconnect ();//Disconnect}
Catch(malformedurlexception e) {//The following exception is specific to the specific processing of e.printstacktrace (); } Catch(IOException e) {e.printstacktrace (); } returndata; }

The above is basically a small process to get the data and convert it into an entity class.

The following is a description of the entity class build and Param parameters

Entity class:

Query criteria given by the other party:

q={
"Devchnid": "[Email protected]$1$0$0",
"StartDate": "2015-12-11 17:01:10",
"EndDate": "2015-12-12 17:01:10"
}

I built the query parameter entity class as follows:

 Public classSearchparam {PrivateString Devchnid; PrivateString StartDate; PrivateString endDate;  PublicString Getdevchnid () {returnDevchnid; }     Public voidSetdevchnid (String devchnid) { This. Devchnid =Devchnid; }     PublicString getstartdate () {returnStartDate; }     Public voidsetstartdate (String startdate) { This. StartDate =StartDate; }     PublicString getenddate () {returnendDate; }     Public voidsetenddate (String endDate) { This. endDate =endDate; } @Override Publicstring toString () {string str=""; Try{str=urlencoder.encode ("{\" devchnid\ ": \" "+devchnid+" \ ", \" startdate\ ": \" "+startdate+" \ ", \" enddate\ ": \" "+enddate+" \ " } "," UTF-8 "); } Catch(unsupportedencodingexception e) {//TODO auto-generated Catch blockE.printstacktrace (); }        return"Q=" +str; }    }

The override of the ToString method in the above entity class code is a special setting for the Param parameter

In the string "need to use \" escaped, specifically need to escape the symbol can query <a href= "http://blog.csdn.net/lanchengxiaoxiao/article/details/41893925" > Related information </a>

My writing here is actually more silly, can also be said to be relatively primitive, the previous mentioned Gson can be the entity class built into the JSON format

Using Gson can be written in the following way, Gson the class is actually output is a string string

 Public String toString () {        returnnew Gsonbuilder (). Create (). ToJson (this);    }
The following is the test return result
{"Devchnid": "#[email Protected]", "StartDate": "2011-12-15 12:23:43", "endDate": "2016-12-12 12:02:24"}

But this only gets the JSON-formatted parameters, and when you make a GET request, it returns a 400 error, because there may be some characters that are not recognized in the URL parameter

So you need to use Urlencoder.encode () for URL encoding, but the prefix "q=" does not need to be encoded to prevent the identification of parameters that are get mode

The road to Java development 2016.12.26

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.