Android json implements Security Authentication for network requests and common http requests as well as https requests, androidjson

Source: Internet
Author: User

Android json implements Security Authentication for network requests and common http requests as well as https requests, androidjson

There are many http requests for android, so you need to know how to connect to the server.

In Android, the Android SDK has encapsulated the entire JSON-related operation for us, which is very convenient to use.

Directly Add code

/**
* Send an 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); // sets the Parameter
}
Try {
StringEntity se = new StringEntity (param. toString (), "UTF-8"); // prevents garbled characters
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); // you can specify headers.
Request. setHeader ("X-FBox-ClientId", ClientId );
Request. setHeader ("Content-Type ",
"Application/json; charsets = UTF-8 ");
// Send the request
Try {
HttpResponse httpResponse = new DefaultHttpClient ()
. Execute (request );

// String retSrc = EntityUtils. toString (httpResponse. getEntity (); // return the result

ResponseCode = httpResponse. getStatusLine (). getStatusCode (); // return status
} Catch (ClientProtocolException e ){
// TODO Auto-generated catch block
E. printStackTrace ();
} Catch (IOException e ){
// TODO Auto-generated catch block
E. printStackTrace ();
}
} Catch (JSONException e ){
// TODO Auto-generated catch block
E. printStackTrace ();
}
Return responseCode;
}

The entire process is basically included here. And some garbled issues.

The following section describes common http requests.

/**
* Send an 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 Method to "POST"
Con. setRequestMethod (httpMethod );
// When the parameter value is true, the current link can be submitted for data.
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 the 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 a request method of the application/x-www-form-urlencoded type.

Here is just a normal request http

Sometimes when we encounter an https request, we only need to 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 any certificate
*/
@ SuppressLint ("TrulyRandom ")
Private static void trustAllHosts (){
// Create a trust manager that does not validate certificate chains
// Android uses the X509 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
. Setdefadefasslsocketfactory (SC. getSocketFactory ());
} Catch (Exception e ){
E. printStackTrace ();
}
}

In this way, you can access https requests with certificates.

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.