2013-03-20 4 views
4

У меня возникла проблема с доступом к службам Microsoft Translator, которая обеспечит ограничение оставшихся символов.Как позвонить https://api.datamarket.azure.com/Services/My/Datasets для получения ResourceBalance

Я сделал маркер доступа к части, только дело в том, чтобы получить информацию о наборах данных пользователя по телефону

https://api.datamarket.azure.com/Services/My/Datasets обслуживания.

Я передал этот link

ответ

4

Есть 2 способа санкционируют для получения баланса ресурсов

  1. с помощью OAuth (требуется токен аутентификации)
  2. с помощью Basic (требуется ключ счета)

Основной процесс авторизации

import java.io.BufferedReader; 
import java.io.InputStreamReader; 
import java.net.URL; 
import java.net.URLConnection; 
import org.apache.commons.codec.binary.Base64; 

public class MSTranslaterUserInforService { 
    public static void main(String[] args) throws Exception { 
     String bingUrl = "https://api.datamarket.azure.com/Services/My/Datasets?$format=json"; 
     String accountKey = "place your account_key here"; 
     byte[] accountKeyBytes = Base64 
       .encodeBase64((accountKey + ":" + accountKey).getBytes()); 
     String accountKeyEnc = new String(accountKeyBytes); 
     URL urlb = new URL(bingUrl); 
     URLConnection urlConnection = urlb.openConnection(); 
     urlConnection.setRequestProperty("Authorization", "Basic " 
       + accountKeyEnc); 
     String line; 
     BufferedReader reader = new BufferedReader(new InputStreamReader(
       urlConnection.getInputStream())); 
     line = reader.readLine(); 
     System.out.println(line); 
    } 
} 
1

Поскольку язык не указан, он охватывает сторону C#.

Это включает в себя быстрый & грязный (текущий с 2013-12-05) Разбор XML для извлечения подсчета ресурсов Microsoft Translator.

using System; 
using System.Collections.Generic; 
using System.Linq; 
using System.Text; 
using System.Net; 
using System.Xml; 
using System.IO; 

namespace translation_testing 
{ 
    class Class1 
    { 
     public static int GetUsage() 
     { 
      string uri = "https://api.datamarket.azure.com/Services/My/Datasets"; 
      string general_accountkey = "your account key"; 

      string accountkeyraw = general_accountkey + ":" + general_accountkey; 
      byte[] accountkeybytes = Encoding.UTF8.GetBytes(accountkeyraw); 
      string accountkeystring = Convert.ToBase64String(accountkeybytes); 

      HttpWebRequest httpWebRequest = (HttpWebRequest)WebRequest.Create(uri); 
      httpWebRequest.Headers.Add("Authorization", "Basic " + accountkeystring); 

      WebResponse response = null; 
      try 
      { 
       response = httpWebRequest.GetResponse(); 
       using (Stream stream = response.GetResponseStream()) 
       { 
        StringBuilder sbresponse = new StringBuilder(); 
        int len = 1; 
        while (stream.CanRead && len > 0) 
        { 
         byte[] chunk = new byte[4096]; 
         len = stream.Read(chunk, 0, 4096); 
         sbresponse.Append(Encoding.UTF8.GetString(chunk, 0, len)); 
        } 

        return translator_resource_count(sbresponse.ToString()); 
       } 
      } 
      catch 
      { 
       throw; 
      } 
      finally 
      { 
       if (response != null) 
       { 
        response.Close(); 
        response = null; 
       } 
      } 
     } 

     private static int translator_resource_count(string input) 
     { 
      bool isentry = false; 
      bool iscontent = false; 
      bool istitle = false; 
      bool isbalance = false; 

      string title = null; 
      string balance = null; 

      using (XmlReader reader = XmlReader.Create(new StringReader(input))) 
      { 
       while (reader.Read()) 
       { 
        if (reader.NodeType == XmlNodeType.Text) 
        { 
         if (istitle) title = reader.Value; 
         if (isbalance) balance = reader.Value; 
        } 
        else if (reader.NodeType == XmlNodeType.Element) 
        { 
         if (reader.Name == "entry") isentry = true; 
         if (isentry && reader.Name == "content") iscontent = true; 
         if (isentry && !iscontent && reader.Name == "title") istitle = true; 
         if (isentry && iscontent && title == "Microsoft Translator" && reader.Name == "d:ResourceBalance") isbalance = true; 
        } 
        else if (reader.NodeType == XmlNodeType.EndElement) 
        { 
         if (reader.Name == "entry") isentry = false; 
         if (isentry && reader.Name == "content") iscontent = false; 
         if (isentry && !iscontent && reader.Name == "title") istitle = false; 
         if (isentry && iscontent && title == "Microsoft Translator" && reader.Name == "d:ResourceBalance") isbalance = false; 
        } 
       } 
      } 

      return int.Parse(balance); 
     } 

    } 
}