使用VB.NET调用TeamViewer REST API获取设备列表及修改别名
Got it, let's work through your TeamViewer API needs step by step. You're right about the 401 error—you need to properly authenticate using OAuth 2.0 with your Client ID, Client Secret, and authorization code instead of a hardcoded token. I'll show you how to get a valid access token, fetch your device list, and update device aliases using VB.NET.
1. Fix the 401 Error: Get a Valid Access Token
First, you need to request an access token from TeamViewer's OAuth endpoint. This replaces the static token you were using and fixes the unauthorized error. Here's the code:
Imports System.Net Imports System.Text Private Function GetTeamViewerAccessToken(clientId As String, clientSecret As String, authorizationCode As String) As String Dim tokenUrl As String = "https://webapi.teamviewer.com/api/v1/oauth2/token" ' Build form data required for token request Dim formData As String = $"grant_type=authorization_code&client_id={clientId}&client_secret={clientSecret}&code={authorizationCode}" Dim byteData As Byte() = Encoding.UTF8.GetBytes(formData) Try Dim request As HttpWebRequest = CType(WebRequest.Create(tokenUrl), HttpWebRequest) request.Method = "POST" request.ContentType = "application/x-www-form-urlencoded" request.ContentLength = byteData.Length ' Write form data to request stream Using stream = request.GetRequestStream() stream.Write(byteData, 0, byteData.Length) End Using ' Parse the token from JSON response Using response As HttpWebResponse = CType(request.GetResponse(), HttpWebResponse) Using reader As New StreamReader(response.GetResponseStream()) Dim jsonResponse As String = reader.ReadToEnd() ' Use Newtonsoft.Json to parse (install via NuGet Package Manager) Dim tokenObj = Newtonsoft.Json.JsonConvert.DeserializeObject(Of Dictionary(Of String, Object))(jsonResponse) Return tokenObj("access_token").ToString() End Using End Using Catch ex As Exception MsgBox($"Token request failed: {ex.Message}") Return Nothing End Try End Function
Note: You'll need to install the
Newtonsoft.JsonNuGet package to parse JSON responses. Go to Tools > NuGet Package Manager > Manage NuGet Packages for Solution and search for it.
2. Fetch All Devices in Your Admin Account
With a valid access token, modify your original GET request to fetch and parse the device list:
Imports Newtonsoft.Json Private Sub FetchTeamViewerDevices(accessToken As String) Dim apiVersion As String = "v1" Dim tvApiBaseUrl As String = "https://webapi.teamviewer.com" Dim address As String = $"{tvApiBaseUrl}/api/{apiVersion}/devices" Try Dim request As HttpWebRequest = CType(WebRequest.Create(address), HttpWebRequest) request.Headers.Add("Authorization", $"Bearer {accessToken}") ' Correct auth header format request.Method = "GET" request.Accept = "application/json" Using webResp As HttpWebResponse = CType(request.GetResponse(), HttpWebResponse) Using reader As New StreamReader(webResp.GetResponseStream()) Dim jsonDevices As String = reader.ReadToEnd() ' Parse JSON into a list of devices (use a class for better type safety if needed) Dim devices = Newtonsoft.Json.JsonConvert.DeserializeObject(Of List(Of Dictionary(Of String, Object)))(jsonDevices) ' Example: Loop through devices and display IDs/aliases For Each device In devices Dim deviceId As String = device("id").ToString() Dim alias As String = If(device.ContainsKey("alias"), device("alias").ToString(), "No alias set") MsgBox($"Device ID: {deviceId}, Alias: {alias}") Next End Using End Using Catch ex As Exception MsgBox($"Failed to fetch devices: {ex.ToString()}") End Try End Sub
Tip: For cleaner code, create a
Deviceclass with properties likeId,Alias,OnlineStatus, etc., and deserialize directly to that instead of using a Dictionary.
3. Update a Device Alias with PUT Request
To modify a device's alias using values from your text boxes, use this PUT request code:
Private Sub UpdateDeviceAlias(accessToken As String, deviceId As String, newAlias As String) Dim apiVersion As String = "v1" Dim tvApiBaseUrl As String = "https://webapi.teamviewer.com" Dim address As String = $"{tvApiBaseUrl}/api/{apiVersion}/devices/{deviceId}" ' Build JSON request body with the new alias Dim requestBody As String = $"{{""alias"": ""{newAlias}""}}" Dim byteData As Byte() = Encoding.UTF8.GetBytes(requestBody) Try Dim request As HttpWebRequest = CType(WebRequest.Create(address), HttpWebRequest) request.Headers.Add("Authorization", $"Bearer {accessToken}") request.Method = "PUT" request.ContentType = "application/json" request.ContentLength = byteData.Length ' Write JSON body to request stream Using stream = request.GetRequestStream() stream.Write(byteData, 0, byteData.Length) End Using ' Verify update success Using response As HttpWebResponse = CType(request.GetResponse(), HttpWebResponse) If response.StatusCode = HttpStatusCode.OK Then MsgBox("Device alias updated successfully!") Else MsgBox($"Update failed: {response.StatusDescription}") End If End Using Catch ex As Exception MsgBox($"Error updating alias: {ex.ToString()}") End Try End Sub
How to Use These Functions
Call them from your form buttons (replace placeholders with your actual API credentials):
Private Sub btnFetchDevices_Click(sender As Object, e As EventArgs) Handles btnFetchDevices.Click Dim clientId As String = "YOUR_TEAMVIEWER_CLIENT_ID" Dim clientSecret As String = "YOUR_TEAMVIEWER_CLIENT_SECRET" Dim authCode As String = "YOUR_AUTHORIZATION_CODE" Dim accessToken As String = GetTeamViewerAccessToken(clientId, clientSecret, authCode) If Not String.IsNullOrEmpty(accessToken) Then FetchTeamViewerDevices(accessToken) End If End Sub Private Sub btnUpdateAlias_Click(sender As Object, e As EventArgs) Handles btnUpdateAlias.Click Dim clientId As String = "YOUR_TEAMVIEWER_CLIENT_ID" Dim clientSecret As String = "YOUR_TEAMVIEWER_CLIENT_SECRET" Dim authCode As String = "YOUR_AUTHORIZATION_CODE" Dim accessToken As String = GetTeamViewerAccessToken(clientId, clientSecret, authCode) If Not String.IsNullOrEmpty(accessToken) Then UpdateDeviceAlias(accessToken, TextBox2.Text, TextBox1.Text) End If End Sub
Important: Ensure your TeamViewer API app has the correct permissions (
device_listanddevice_management) enabled in the TeamViewer Developer Portal to avoid permission errors.
内容的提问来源于stack exchange,提问作者Nrodgers1987

