Java web api call and javawebapi

Source: Internet
Author: User

Java web api call and javawebapi
Web Services is standardized by W3C.

Web Services can be published to a Global Registry and automatically provide service URLs, service descriptions, interface call requirements, parameter descriptions, and return value descriptions. For example, the China Meteorological Administration can publish weather forecast services. If you want to integrate the weather forecast function with other websites or mobile apps, you can access the Web Service to obtain data.

Web Services is designed to provide public Services.

All Web Services are based on XML. Describes all aspects of the service (parameters, parameter transfer, return values, and Service Release discovery) According to W3C standards ). To clearly describe all aspects of Web Services standards, a 2000-page document may be required.
Web Services also provides standard authentication methods (for non-public Services, user identities are verified ).

Lightweight Web APIs

The private service used inside the company, we know its interface Url, so we do not need to automatically discover it. We have its service interface documentation, so it does not need to be automatically described or called.
Even if the features of Web Services (automatic discovery and automatic learning of calling methods) are good, private Services often do not need these features.

Web APIs are generally implemented based on HTTP/REST and do not need to be defined. parameters (input data) can be JSON, XML, or simple text, and responses (output data) it is generally JSON or XML. It does not provide service call standards and service discovery standards. Some simple instructions can be provided to users based on the characteristics of your service.

The way to obtain remote data is changing from Web Services to Web APIs.

The architecture of Web Services is much bloated than that of Web APIs. Every request of Web Services needs to be encapsulated into XML and unblocked on the server. Therefore, it is difficult to develop and consume more resources (memory and bandwidth ). The performance is not as good as that of Web APIs.

 

/**
* Encode the string based on the specified url
*
* @ Param address
* @ Param Charset
* @ Return
*/
Public static String getStringByConAndCharset (String address, String Charset ){

StringBuffer sb;
Try {
URL url = new URL (address );

URLConnection con = url. openConnection ();
BufferedReader bw = new BufferedReader (new InputStreamReader (con. getInputStream (), Charset ));
String line;
Sb = new StringBuffer ();
While (line = bw. readLine ())! = Null ){
Sb. append (line + "\ n ");
}
Bw. close ();
} Catch (Exception e ){
E. printStackTrace ();
Sb = new StringBuffer ();
}

Return sb. toString ();
}

/**
* Obtain the page source code through post
*
* @ Param urlString
* Url
* @ Param paramContent
* Post Parameters
* @ Param chartSet
* Character encoding (ISO-8859-1 by default)
* @ Return
* @ Throws IOException
*/
Public static String postUrl (String urlString, String paramContent, String chartSet, String contentType ){
Long beginTime = System. currentTimeMillis ();
If (chartSet = null | "". equals (chartSet )){
ChartSet = "ISO-8859-1 ";
}

StringBuffer result = new StringBuffer ();
BufferedReader in = null;

Try {
URL url = new URL (urlString ));
URLConnection con = url. openConnection ();

// Set link timeout
Con. setConnectTimeout (3000 );
// Set read timeout
Con. setReadTimeout (3000 );
// Set parameters
Con. setDoOutput (true );
If (contentType! = Null &&! "". Equals (contentType )){
Con. setRequestProperty ("Content-type", contentType );
}

OutputStreamWriter writer = new OutputStreamWriter (con. getOutputStream (), chartSet );
Writer. write (paramContent );
Writer. flush ();
Writer. close ();
In = new BufferedReader (new InputStreamReader (con. getInputStream (), chartSet ));
String line = null;
While (line = in. readLine ())! = Null ){
Result. append (line + "\ r \ n ");
}
In. close ();
} Catch (MalformedURLException e ){
Logger. error ("Unable to connect to URL:" + urlString, e );
} Catch (SocketTimeoutException e ){
Logger. error ("Timeout Exception when connecting to URL:" + urlString, e );
} Catch (IOException e ){
Logger. error ("IOException when connecting to URL:" + urlString, e );
} Finally {
If (in! = Null ){
Try {
In. close ();
} Catch (Exception ex ){
Logger. error ("Exception throws at finally close reader when connecting to URL:" + urlString, ex );
}
}
Long endTime = System. currentTimeMillis ();
Logger.info ("post time:" + (endTime-beginTime) + "ms ");
}
Return result. toString ();
}

/**
* Send an https request
* @ Param requestUrl: request address
* @ Param requestMethod: Request Method (GET, POST)
* @ Param outputStr: Data Submitted
* @ Return JSONObject (get THE json object attribute value through JSONObject. get (key)
* @ Throws NoSuchProviderException
* @ Throws NoSuchAlgorithmException
*/
Public static JSONObject httpsRequest (String requestUrl, String requestMethod, String outputStr) throws Exception {
JSONObject json = null;
// Create an SSLContext object and use the specified trust manager to initialize the object
TrustManager [] tm = {new MyX509TrustManager ()};
SSLContext sslContext = SSLContext. getInstance ("SSL", "SunJSSE ");
SslContext. init (null, tm, new java. security. SecureRandom ());
// Obtain the SSLSocketFactory object from the SSLContext object
SSLSocketFactory ssf = sslContext. getSocketFactory ();

URL url = new URL (requestUrl );
HttpsURLConnection conn = (HttpsURLConnection) url. openConnection ();
Conn. setSSLSocketFactory (ssf );

Conn. setDoOutput (true );
Conn. setDoInput (true );
Conn. setUseCaches (false );
// Set the Request Method (GET/POST)
Conn. setRequestMethod (requestMethod );

// Write data to the output stream when outputStr is not null
If (null! = OutputStr ){
OutputStream outputStream = conn. getOutputStream ();
// Pay attention to the encoding format
OutputStream. write (outputStr. getBytes ("UTF-8 "));
OutputStream. close ();
}

// Read the returned content from the input stream
InputStream inputStream = conn. getInputStream ();
InputStreamReader inputStreamReader = new InputStreamReader (inputStream, "UTF-8 ");
BufferedReader bufferedReader = new BufferedReader (inputStreamReader );
String str = null;
StringBuffer buffer = new StringBuffer ();
While (str = bufferedReader. readLine ())! = Null ){
Buffer. append (str );
}

// Release resources
BufferedReader. close ();
InputStreamReader. close ();
InputStream. close ();
InputStream = null;
Conn. disconnect ();
Json = JSON. parseObject (buffer. toString ());
String errcode = json. getString ("errcode ");
If (! StringUtil. isBlank (errcode )&&! Errcode. equals ("0 ")){
Logger. error (json. toString ());
Throw new SysException ("ERRCODE:" + errcode );
}
Return json;
}

}

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.