Android JSON implements network requests and normal HTTP requests with HTTPS request Security authentication

Source: Internet
Author: User

Android implements HTTP requests many kinds, and server docking needs to understand

Under Android, the Android SDK has encapsulated the entire JSON-related operation for us and is very easy to use

Directly on the code

/**
* Send HTTP request
*
* @param URL
*/
@SuppressLint ("Defaultlocale")
public int Httpresponsecodejsonpost (string strurl, string authorization,
String Currentsessionid, String ClientId,
Postparameter[] Postparams, String HttpMethod)
Throws SystemException {
int responsecode =-1;
try {
HttpPost request = new HttpPost (strURL);
Jsonobject param = new Jsonobject ();
for (int j = 0; J < Postparams.length; J + +) {
Param.put (Postparams[j].name,
Postparams[j].value);//Setting parameters
}
try {
Stringentity se = new stringentity (param.tostring (), "utf-8");//Prevent garbled
Request.setentity (SE);
} catch (Unsupportedencodingexception E1) {
TODO auto-generated Catch block
E1.printstacktrace ();
}
Request.getparams (). Setparameter (Coreconnectionpnames.connection_timeout, 5000);
Request.getparams (). Setparameter (Coreconnectionpnames.so_timeout, 5000);//Set timeout
Request.setheader ("X-fbox-session", Currentsessionid);
Request.setheader ("Authorization", Authorization);//Set various headers
Request.setheader ("X-fbox-clientid", ClientId);
Request.setheader ("Content-type",
"Application/json;charset=utf-8");
Send Request
try {
HttpResponse HttpResponse = new Defaulthttpclient ()
. Execute (Request);

String retsrc = entityutils.tostring (Httpresponse.getentity ()); return results

ResponseCode = Httpresponse.getstatusline (). Getstatuscode ();//Returns the status
} catch ( Clientprotocolexception e) {
//TODO auto-generated catch block
e.printstacktrace ();
} catch (IOException e) {
//TODO Auto-generated Catch block
e.printstacktrace ();
}
} catch (Jsonexception e) {
Span style= "White-space:pre" >
//TODO auto-generated catch block
E.printstacktrace ();
}
return responsecode;
}

This basically includes the whole process. And some considered garbled problems.

The following paragraph is a normal HTTP request

/**
* Send HTTP request
*
* @param URL
*/
@SuppressLint ("Defaultlocale")
public int Httpresponsecode (string strurl, string authorization,
String Currentsessionid, String ClientId,
Postparameter[] Postparams, String HttpMethod)
Throws SystemException {
int retriedcount;
int retry = 1;
Response res = null;
int responsecode =-1;
for (retriedcount = 0; retriedcount < retry; retriedcount++) {
try {
HttpURLConnection con = null;
OutputStream OSW = null;
URL url = new URL (strurl);
try {
Con = (httpurlconnection) url.openconnection ();
Con.setdoinput (TRUE);
Con.setrequestproperty ("Authorization", Authorization);

Con.addrequestproperty ("X-fbox-clientid", ClientId);
Setheaders (strURL, Postparams, con, httpmethod);
if ("POST". Equals (HttpMethod) | | "PUT". Equals (HttpMethod)) {//null
Set the current HTTP request mode to "POST"
Con.setrequestmethod (HttpMethod);
A parameter value of true determines that the current link can be submitted for data work
Con.setrequestproperty ("Content-type",
"application/x-www-form-urlencoded");
Con.setdooutput (TRUE);
String Postparam = "";
if (postparams! = null) {
Postparam = Encodeparameters (postparams);
}
byte[] bytes = postparam.getbytes ("UTF-8");
Set file length
Con.setrequestproperty ("Content-length",
Integer.tostring (bytes.length));
OSW = Con.getoutputstream ();
Osw.write (bytes);
Osw.flush ();
Osw.close ();
} else {
Con.setrequestmethod (HttpMethod);
}
Con.setconnecttimeout (this.connectiontimeout);
Con.setreadtimeout (this.readtimeout);
res = new Response (con);
Responsecode = Con.getresponsecode ();
} finally {
try {
Osw.close ();
} catch (Exception ignore) {
}
}
} catch (IOException IoE) {
Connection Timeout or read timeout
if (Retriedcount = = 1) {//RetryCount
throw New SystemException (Ioe.getmessage (), IoE,
Responsecode);
}
}
}
return responsecode;
}

This is how the application/x-www-form-urlencoded type is requested.

This is just a normal request HTTP

Sometimes we come across HTTPS requests that add the following


if (Url.getprotocol (). toLowerCase (). Equals ("https")) {
Trustallhosts ();//Trust All
Httpsurlconnection HTTPS = (httpsurlconnection) URL
. OpenConnection ();
Https.sethostnameverifier (do_not_verify);
con = HTTPS;
} else {
Con = (httpurlconnection) url.openconnection ();
}


/**
* Trust all hosts-do not check for any certificates
*/
@SuppressLint ("Trulyrandom")
private static void Trustallhosts () {
Create a trust manager that does not validate certificate chains
Android uses X509 's certificate information mechanism
trustmanager[] Trustallcerts = new trustmanager[] {new X509trustmanager () {
Public java.security.cert.x509certificate[] Getacceptedissuers () {
return new java.security.cert.x509certificate[] {};
}


public void checkclienttrusted (x509certificate[] chain,
String authtype) throws Certificateexception {
}


public void checkservertrusted (x509certificate[] chain,
String authtype) throws Certificateexception {
}
} };


Install the All-trusting trust manager
try {
Sslcontext sc = sslcontext.getinstance ("TLS");
Sc.init (NULL, Trustallcerts, New Java.security.SecureRandom ());
Httpsurlconnection
. Setdefaultsslsocketfactory (Sc.getsocketfactory ());
} catch (Exception e) {
E.printstacktrace ();
}
}

This allows access to the HTTPS request with the certificate

Android JSON implements network requests and normal HTTP requests with HTTPS request Security authentication

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.