1.Net Call URL Interface Service
Using system;using system.collections;using system.configuration;using system.data;using System.Web;using System.web.security;using system.web.ui;using system.web.ui.htmlcontrols;using System.Web.UI.WebControls;using system.web.ui.webcontrols.webparts;using system.text;using system.net;using System.io;public partial class _Default: system.web.ui.page{/******************************************************************************************* ///Request Data Interface/**************************************************************************************** /#region Request data Interface protected void Send () {string Url= "Http://apis.juhe.cn/ip/ip2add R "; Data URL String ip = "www.juhe.cn"; The IP address that needs to be queried string appkey = "Xxxxxxxxxxxxxxxxxxxx"; StringBuilder sbtemp = new StringBuilder (); POST Pass Value sbtemp.append ("ip=" +ip+ "&appkey=" + Appkey); byte[] Btemp = System.teXt. Encoding.GetEncoding ("UTF-8"). GetBytes (Sbtemp.tostring ()); String Postreturn = dopostrequest (URL, btemp); Response.Write ("Post Response is:" + Postreturn); The test returns the result jsonobject NEWOBJ = new Jsonobject (Postreturn); String ErrorCode = newobj[' Error_code ']. Value; if (ErrorCode = = ' 0 ') {//Successful request Response.Write (newobj[' result ' [' area ']); }else{//request failed, error reason Response.Write (newobj[' reason '). Value); }}//post method sent results private static string dopostrequest (string URL, byte[] bdata) {System.Net.HttpWebReq Uest hwrequest; System.Net.HttpWebResponse Hwresponse; String strresult = String. Empty; try {hwrequest = (System.Net.HttpWebRequest) System.Net.WebRequest.Create (URL); Hwrequest.timeout = 5000; Hwrequest.method = "POST"; HwrequeSt. ContentType = "application/x-www-form-urlencoded"; Hwrequest.contentlength = Bdata.length; System.IO.Stream smwrite = Hwrequest.getrequeststream (); Smwrite.write (bdata, 0, bdata.length); Smwrite.close (); } catch (System.Exception err) {Writeerrlog (err. ToString ()); return strresult; }//get response try {hwresponse = (HttpWebResponse) hwrequest.getresponse (); StreamReader Srreader = new StreamReader (Hwresponse.getresponsestream (), Encoding.UTF8); strresult = Srreader.readtoend (); Srreader.close (); Hwresponse.close (); } catch (System.Exception err) {Writeerrlog (err. ToString ()); } return strresult; } private static void Writeerrlog (String strerr) {Console.WriteLine (strerr); System.Diagnostics.Trace.WriteLine (STRERR); } #endregion}
2.c# calling the URL interface service
Using system;using system.collections.generic;using system.linq;using system.text;using System.Net.Security;using System.security.cryptography.x509certificates;using system.net;using system.io;using System.IO.Compression;using System.text.regularexpressions;using System.web.script.serialization;namespace IP{class Program {private St atic readonly String defaultuseragent = "mozilla/4.0 (compatible; MSIE 6.0; Windows NT 5.2; SV1;. NET CLR 1.1.4322;. NET CLR 2.0.50727) "; static void Main (string[] args) {string appKey = "##########################";//the corresponding key s for the application Tring IP = "www.juhe.cn"; String tagurl = "http://apis.juhe.cn/ip/ip2addr?ip=" + IP + "&key=" + AppKey; Cookiecollection cookies = new Cookiecollection (); HttpWebResponse response = Creategethttpresponse (tagurl, NULL, NULL, cookies); StreamReader sr = new StreamReader (response. GetResponseStream (), Encoding.UTF8); String retValue = Sr. ReadToEnd (); Sr. Close (); var serializer = new JavaScriptSerializer (); ipobj ret = serializer. Deserialize<ipobj> (RetValue); BOOL result = Ret.error_code. Equals ("0", stringcomparison.ordinal); if (result) {Console.Write (ret.result.location + "" + Ret.result.area); } else {Console.Write ("Error_code:" +ret.error_code+ ", Reason:" +ret.reason); }}///<summary>//Create a Get method HTTP request////</summary>//<param Name= "url" > Requested url</param>//<param name= "Timeout" > Request time-out </param>//<param Name= "useragent" > client browser information requested, can be null </param>//<param name= "cookies" > Cookie information sent with HTTP request, if no authentication is required Think empty </param>///<returns></returns> public static HttpWebResponse Creategethttprespons E (string url, int? Timeout, string useragent, Cookiecollection cookie) {if (string. IsNullOrEmpty (URL)) {throw new ArgumentNullException ("url"); } HttpWebRequest request = WebRequest.Create (URL) as HttpWebRequest; Request. Method = "GET"; Request. useragent = defaultuseragent; if (!string. IsNullOrEmpty (useragent)) {request. useragent = useragent; } if (timeout. HasValue) {request. Timeout = timeout. Value; } if (cookie = null) {request. Cookiecontainer = new Cookiecontainer (); Request. Cookiecontainer.add (cookies); } return request. GetResponse () as HttpWebResponse; }} class Ipobj {public string Error_code {get; set;} public string Reason {get; set;} Public result result {get; set;} } class Result{public string area {get; set;} public string location {get; set;} }}
3.Java calling URL interface service
Package Com.test;import Java.io.bufferedreader;import Java.io.inputstream;import java.io.inputstreamreader;import Java.net.httpurlconnection;import Java.net.url;import Net.sf.json.jsonobject;public class Demo {public static void Mai N (string[] args) {String city = "Suzhou";//parameter String URL = "http://web.juhe.cn:8080/environment/air/cityair?city=";// The URL is the API interface address of the request String key= "################################";//the corresponding keystring Urlall = new StringBuffer (URL) of the application. Append ( City). Append ("&key="). Append (Key). ToString (); String charset = "UTF-8"; String jsonresult = Get (Urlall, CharSet);//Get JSON string Jsonobject object = Jsonobject.fromobject (Jsonresult);// Convert to JSON class string code = object.getstring ("Error_code"),//Get error code//error code to determine if (Code.equals ("0")) {//Get data as needed Jsonobject Jsonobject = (jsonobject) object.getjsonarray ("result"). Get (0); System.out.println (Jsonobject.getjsonobject ("Citynow"). Get ("AQI")); Else{system.out.println ("Error_code:" +code+ ", Reason:" +object.getstring ("Reason"));}} /** * * @paraM Urlall: Request interface * @param charset: Character encoding * @return returns JSON result */public static string get (String urlall,string charset {BufferedReader reader = null; String result = null; StringBuffer SBF = new StringBuffer (); String useragent = "mozilla/5.0 (Windows NT 6.1) applewebkit/537.36 (khtml, like Gecko) chrome/29.0.1547.66 safari/537.36" ;//Emulation browser try {URL url = new URL (urlall); HttpURLConnection connection = (httpurlconnection) url.openconnection (); Connection.setrequestmethod ("GET"); Connection.setreadtimeout (30000); Connection.setconnecttimeout (30000); Connection.setrequestproperty ("User-agent", useragent); Connection.connect (); InputStream is = Connection.getinputstream (); reader = new BufferedReader (new InputStreamReader (IS, CharSet)); String Strread = Null;while ((Strread = Reader.readline ()) = null) {sbf.append (strread); Sbf.append ("\ r \ n");} Reader.close (); result = Sbf.tostring (); } catch (Exception e) {e.printstacktrace ();} return result; }}
Invoking the URL interface service