调用URL 接口服务

1.Net调用URL 接口服务

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
{

    /********************************************************************************************************/
    //请求数据接口
    /********************************************************************************************************/
    #region 请求数据接口
    protected void send()
    {
                string url="http://apis.juhe.cn/ip/ip2addr"; //数据URL
                string ip = "www.juhe.cn";  //需要查询的IP地址
                string appkey = "xxxxxxxxxxxxxxxxxxxx";
                StringBuilder sbTemp = new StringBuilder();
				
                //POST 传值
                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);  //测试返回结果

                JsonObject newObj = new JsonObject(postReturn);
                String errorCode = newObj['error_code'].Value;

                if(errorCode =='0'){
                    //成功的请求
                    Response.Write(newObj['result']['area']);
                }else{
                    //请求失败,错误原因
                    Response.Write(newObj['reason'].Value);
                }
    }
    //POST方式发送得结果
    private static String doPostRequest(string url, byte[] bData)
    {
        System.Net.HttpWebRequest 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#调用URL接口服务

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 static 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 = "##########################"; //申请的对应的KEY
            string 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>  
        /// 创建GET方式的HTTP请求  
        /// </summary>  
        /// <param name="url">请求的URL</param>  
        /// <param name="timeout">请求的超时时间</param>  
        /// <param name="userAgent">请求的客户端浏览器信息,可以为空</param>  
        /// <param name="cookies">随同HTTP请求发送的Cookie信息,如果不需要身份验证可以为空</param>  
        /// <returns></returns>  
        public static HttpWebResponse CreateGetHttpResponse(string url, int? timeout, string userAgent, CookieCollection cookies)
        {
            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 (cookies != 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调用URL接口服务

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 main(String[] args) {
	String city = "suzhou";//参数
	String url = "http://web.juhe.cn:8080/environment/air/cityair?city=";//url为请求的api接口地址
    String key= "################################";//申请的对应key
	String urlAll = new StringBuffer(url).append(city).append("&key=").append(key).toString(); 
	String charset ="UTF-8";
	String jsonResult = get(urlAll, charset);//得到JSON字符串
	JSONObject object = JSONObject.fromObject(jsonResult);//转化为JSON类
	String code = object.getString("error_code");//得到错误码
	//错误码判断
	if(code.equals("0")){
		//根据需要取得数据
		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:请求接口
    * @param charset:字符编码
    * @return 返回json结果
    */
   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";//模拟浏览器
	   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;
   }
}

  

posted @ 2015-08-21 10:46  一杯水M  阅读(1242)  评论(0编辑  收藏  举报