API开发语言调用示例

API开发语言调用示例

1.C++调用示例

#include <iostream>
#include <string>
#include <cpprest/http_client.h>
int main()
{
std::string url = "url";
    try
    {
        web::http::client::http_client client(web::uri(utility::conversions::to_string_t(url)));
        web::http::http_response response = client.request(web::http::methods::GET).get();

        concurrency::streams::stringstreambuf buffer;
        response.body().read_to_end(buffer).get();
        std::string& str = buffer.collection();
        std::cout << "ip location result:"<<str<<std::endl;
    }
    catch (std::exception& e)
    {
        std::cout << "Exception: " << e.what() << std::endl;
    }
}
注:
1)安装cpprest、boost_system第三方库
2)编译需要加上第三方库依赖 -lcpprest -lboost_system -lssl -lcrypto -lstdc++ -std=c++11

2.PHP调用示例

<?php
$data = array ();
$data_encode = json_encode($data);
$opts = array (
	'http' => array (
		'method' => 'POST',
		'header'=> "Content-type: application/json",
		'content' => $data_encode
	)
);
$context = stream_context_create($opts);
$html = file_get_contents('url', false, $context);
echo $html;
?>

3.python调用示例

import urllib2
import urllib
import json

data = {}
headers = {"Content-Type": "application/json"}
request = urllib2.Request(url="url",
	data=json.dumps(data), headers=headers)
response = urllib2.urlopen(request)
print response.read()
response.close()

4.C#调用示例

using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Net;
using System.Text;
using System.Threading.Tasks;

namespace ConsoleApp1
{
    class Program
    {
        static void Main(string[] args) {
            string Url = "url";
            string contentType = "application/json";
            string retString = string.Empty;
            HttpWebRequest request = (HttpWebRequest)WebRequest.Create(Url);
            request.Method = "GET";
            request.ContentType = contentType;
            HttpWebResponse response = (HttpWebResponse)request.GetResponse();
            Stream myResponseStream = response.GetResponseStream();
            StreamReader streamReader = new StreamReader(myResponseStream);
            retString = streamReader.ReadToEnd();
            streamReader.Close();
            myResponseStream.Close();
            Console.WriteLine(retString);
            Console.ReadLine();
        }
    }
}

5.Java调用示例

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.OutputStreamWriter;
import java.net.HttpURLConnection;
import java.net.URL;
import java.net.URLConnection;

public class HttpUtil {

    /**
     * get请求地址
     */
    public static String doGet(String url) {
        StringBuffer result = new StringBuffer();
        BufferedReader in = null;
        try {
            URL realUrl = new URL(url);
            // 打开和URL之间的连接
            URLConnection connection = realUrl.openConnection();
            connection.setConnectTimeout(60000);
            connection.setReadTimeout(60000);
            // 建立实际的连接
            connection.connect();
            // 定义 BufferedReader输入流来读取URL的响应
            in = new BufferedReader(new InputStreamReader(
                    connection.getInputStream(), "UTF-8"));
            String line;
            while ((line = in.readLine()) != null) {
                result.append(line);
            }
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            try {
                if (in != null) {
                    in.close();
                }
            } catch (Exception e2) {
                e2.printStackTrace();
            }
        }
        return result.toString();
    }

    /**
     * post请求地址
     */
    public static String doPost(String url, String jsonParam) {
        BufferedReader in = null;
        StringBuffer result = new StringBuffer();
        try {
            URL realUrl = new URL(url);// 创建连接
            HttpURLConnection connection = (HttpURLConnection) realUrl
                    .openConnection();
            connection.setDoOutput(true);
            connection.setDoInput(true);
            connection.setUseCaches(false);
            connection.setInstanceFollowRedirects(true);
            connection.setRequestMethod("POST"); // 设置请求方式
            connection.setRequestProperty("Accept", "application/json"); // 设置接收数据的格式
            connection.setRequestProperty("Content-Type", "application/json"); // 设置发送数据的格式
            connection.setConnectTimeout(30000);
            connection.setReadTimeout(30000);
            connection.connect();
            OutputStreamWriter out = new OutputStreamWriter(
                    connection.getOutputStream(), "UTF-8"); // utf-8编码
            out.append(jsonParam);
            out.flush();
            out.close();
            // 定义 BufferedReader输入流来读取URL的响应
            in = new BufferedReader(new InputStreamReader(
                    connection.getInputStream(), "UTF-8"));
            String line;
            while ((line = in.readLine()) != null) {
                result.append(line);
            }
        } catch (IOException e) {
            e.printStackTrace();
        }
        return result.toString();
    }
    public static void main(String[] args) {
        String url = "";
        String getstr = doGet(url);
        System.err.println(getstr);

        String url2 = "";
        String json = "";
        String poststr = doPost(url2,json);
        System.err.println(poststr);
    }
}

  • 1
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值