调用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;
   }
}

  

时间: 2024-08-26 17:56:51

调用URL 接口服务的相关文章

创建和调用webapi接口服务文件

前言 源码地址:https://github.com/kmonkey9006/QuickWebApi 现在项目中用的是webapi,其中有以下问题:    1.接口随着开发的增多逐渐增加相当庞大. 2.接口调用时不好管理. 以上是主要问题,对此就衍生了一个想法: 如果每一个接口都一个配置文件来管理,每个配置文件能清晰表示处理接口文件,地址,参数,返回值,那么通过这个配置文件,就能很好的管理起来我们所有的webapi接口不是吗? 有了这个思路之后就有了以下的实现: 具体实现: 1.核心代码 pub

小程序调用后端接口服务 配置文件详解

前言:为了开发阶段的效率更高,方便项目接口管理,在做web项目时,我们需要把后端提供的接口地址进行配置,这样我们自己在调用时,要方便得多,利己利人.在配置小程序接口地址时,和web的配置大同小异,下面总结几点配置小程序接口地址的思路: 1.所有接口地址,要丢在一个对象里[为了方便下面解释,这里设置一个对象名:config],为什么了,因为要对外暴露,方便外部访问,这样[key:value]方式是最合理的,那就是对象了. 2.真实接口地址,也就是对象键值对的value,要用英文模式下Tab键的上一

java调用url接口

很多简单的接口就是直接一个URl的形式, 怎么调用? HttpClient httpclient=null; PostMethod post=null; try{ httpclient = new HttpClient(); post = new PostMethod(SendUrl); //设置编码方式 post.getParams().setParameter(HttpMethodParams.HTTP_CONTENT_CHARSET,"gbk"); //添加参数 post.add

java程序调用.net接口服务地址的写法

参考文章:http://download.csdn.net/detail/davidiao/7424767 http://www.cnblogs.com/mq0036/p/3554002.html .asmx?wsdl 注意:?wsdl 一定要加上,否则会报错.

SpringCloud微服务之跨服务调用后端接口

SpringCloud微服务系列博客: SpringCloud微服务之快速搭建EurekaServer:https://blog.csdn.net/egg1996911/article/details/78787540 SpringCloud微服务之注册服务至EurekaServer:https://blog.csdn.net/egg1996911/article/details/78859200 SpringCloud微服务之集成thymeleaf访问html页面/静态页面&热部署:https

@FeignClient 调用另一个服务的test环境,实际上却调用了另一个环境testone的接口,这其中牵扯到k8s容器外容器内的问题,注册到eureka上的是容器外的旧版本

今天遇到了很奇葩的问题,我本机的是以test环境启动的,调用另一个服务接口的时候返回参数却不同,调用接口是没错,怎么会这样,排查了很久,发现在eureka上注册的另一个服务是testone环境,而这个人testone是在k8s容器外面, 我部署的另一个服务是在k8s容器内部的.所以,造成了一直在调用k8s容器外同一个服务,实际我要调用k8s内部的这个服务. 下面是截图大概介绍下步骤: 首先,先排查   active profiles 配置启动环境为test, 并确保启动成功(启动成功后的日志显示

php中创建和调用webservice接口示例

这篇文章主要介绍了php中创建和调用webservice接口示例,包括webservice基本知识.webservice服务端例子.webservice客户端例子,需要的朋友可以参考下 作为开发者来讲,要想写webservice接口或者调用别人的webservice接口,首先需要了解什么是webservice.简单说, WebService就是一些站点开放一些服务出来, 也可以是你自己开发的Service, 也就是一些方法, 通过URL,指定某一个方法名,发出请求,站点里的这个服务(方法),接到

Android 开发之Android 应用程序如何调用支付宝接口

1.到支付宝官网,下载支付宝集成开发包 由于android设备一般用的都是无线支付,所以我们申请的就是支付宝无线快捷支付接口.下面是申请的地址以及下载接口开发包的网址:https://b.alipay.com/order/productDetail.htm?productId=2014110308141993(如果链接失效,你可以到支付宝官网商家服务模块中找到 快捷支付(无线)这个服务.)  下载集成开发包(http://download.alipay.com/public/api/base/W

分享一个PHP调用RestFul接口的函数

php越来越前端化,大型系统中的php经常是调用后端服务的接口,这里分享一个函数.希望对大家有用. /** * [http 调用接口函数] * @Date 2016-07-11 * @Author GeorgeHao * @param string $url [接口地址] * @param array $params [数组] * @param string $method [GET\POST\DELETE\PUT] * @param array $header [HTTP头信息] * @par