Phone Validation International C# Rest Code Snippet

Plain text
Copy to clipboard
Open code in new window
EnlighterJS 3 Syntax Highlighter
public static PVIResponse GetPhoneDetails(string Phone, string Country, string Options, string AuthID)
{
//UrlEncode the values that will be sent to the API so that special characters don't break the url like "#" (Which can often be found in addresses where units are involved.)
string Phone = HttpUtility.UrlEncode(Phone);
string Country = HttpUtility.UrlEncode(Country);
string Options = HttpUtility.UrlEncode(Options);
string AuthID = HttpUtility.UrlEncode(AuthID);
//Not using try/catch here because and errors here should bubble up to the calling code and will allow them to see the details of the thrown exception.
Task<PVIResponse> Response = null;
string Message = "";
string parameters = $"Phone={Phone}&Country={Country}&Options={Options}&AuthID={AuthID}";
Response = HttpGet($"https://sws.serviceobjects.com/PVI/GetPhoneDetails?{parameters}");
if (Response == null) //Failover condition, typecode 3 is Service Objects Fatal
{
Message += "Response is null or API Error.TypeCode 3 Error, executing failover to swsbackup.serviceobjects.com;";
Response = HttpGet($"https://swsbackup.serviceobjects.com/PVI/GetPhoneDetails?{parameters}");
if (Response == null) //No Response returned from service, throw new exception.
{
Message += "Response is null on failover API call to swsbackup.serviceobjects.com; Check network access to Service Objects endpoints.";
throw new Exception(Message);
}
else //There is a response so return it. There could be an API error but that will be in the Response.Error object and the end user will see it.
{
if (Response.Result == null)
{
Message += "Response is null on failover API call to swsbackup.serviceobjects.com; Check network access to Service Objects endpoints.";
throw new Exception(Message);
}
if (Response.Result.ProblemDetails != null && Response.Result.ProblemDetails.Status == "500")
{
Message += "Response was 500 on failover API call to swsbackup.serviceobjects.com; Check network access to Service Objects endpoints.";
throw new Exception(Message);
}
return Response.Result;
}
}
else //There is a response so return it. There could be an API error but that will be in the Response.Error object and the end user will see it.
{
if (Response.Result == null || (Response.Result.ProblemDetails != null && Response.Result.ProblemDetails.Status == "500"))
{
Message += "Response is null or API Error.TypeCode 3 Error, executing failover to swsbackup.serviceobjects.com;";
Response = HttpGet($"https://swsbackup.serviceobjects.com/PVI/GetPhoneDetails?{parameters}");
if (Response == null) //No Response returned from service, throw new exception.
{
Message += "Response is null on failover API call to swsbackup.serviceobjects.com; Check network access to Service Objects endpoints.";
throw new Exception(Message);
}
else //There is a response so return it. There could be an API error but that will be in the Response.Error object and the end user will see it.
{
if (Response.Result == null)
{
Message += "Response is null on failover API call to swsbackup.serviceobjects.com; Check network access to Service Objects endpoints.";
throw new Exception(Message);
}
if (Response.Result.ProblemDetails != null && Response.Result.ProblemDetails.Status == "500")
{
Message += "Response was 500 on failover API call to swsbackup.serviceobjects.com; Check network access to Service Objects endpoints.";
throw new Exception(Message);
}
return Response.Result;
}
}
return Response.Result;
}
}
private static async Task<PVIResponse> HttpGet(string requestUrl)
{
ServicePointManager.SecurityProtocol = SecurityProtocolType.Ssl3 | SecurityProtocolType.Tls | SecurityProtocolType.Tls11 | SecurityProtocolType.Tls12;
ServicePointManager.ServerCertificateValidationCallback += (sender, cert, chain, sslPolicyErrors) => true;
HttpClient client = new HttpClient();
var task = Task.Run(() => client.GetAsync(requestUrl));
task.Wait();
HttpResponseMessage response = task.Result;
HttpContent content = response.Content;
string result = content.ReadAsStringAsync().Result;
PVIResponse pVI = new PVIResponse();
if (response.StatusCode == HttpStatusCode.OK)
{
pVI.PhoneDetailsResponse = JsonConvert.DeserializeObject<PhoneDetailsResponse>(result);
return pVI;
}
else
{
pVI.ProblemDetails = JsonConvert.DeserializeObject<ProblemDetails>(result);
return pVI;
}
}
public static PVIResponse GetPhoneDetails(string Phone, string Country, string Options, string AuthID) { //UrlEncode the values that will be sent to the API so that special characters don't break the url like "#" (Which can often be found in addresses where units are involved.) string Phone = HttpUtility.UrlEncode(Phone); string Country = HttpUtility.UrlEncode(Country); string Options = HttpUtility.UrlEncode(Options); string AuthID = HttpUtility.UrlEncode(AuthID); //Not using try/catch here because and errors here should bubble up to the calling code and will allow them to see the details of the thrown exception. Task<PVIResponse> Response = null; string Message = ""; string parameters = $"Phone={Phone}&Country={Country}&Options={Options}&AuthID={AuthID}"; Response = HttpGet($"https://sws.serviceobjects.com/PVI/GetPhoneDetails?{parameters}"); if (Response == null) //Failover condition, typecode 3 is Service Objects Fatal { Message += "Response is null or API Error.TypeCode 3 Error, executing failover to swsbackup.serviceobjects.com;"; Response = HttpGet($"https://swsbackup.serviceobjects.com/PVI/GetPhoneDetails?{parameters}"); if (Response == null) //No Response returned from service, throw new exception. { Message += "Response is null on failover API call to swsbackup.serviceobjects.com; Check network access to Service Objects endpoints."; throw new Exception(Message); } else //There is a response so return it. There could be an API error but that will be in the Response.Error object and the end user will see it. { if (Response.Result == null) { Message += "Response is null on failover API call to swsbackup.serviceobjects.com; Check network access to Service Objects endpoints."; throw new Exception(Message); } if (Response.Result.ProblemDetails != null && Response.Result.ProblemDetails.Status == "500") { Message += "Response was 500 on failover API call to swsbackup.serviceobjects.com; Check network access to Service Objects endpoints."; throw new Exception(Message); } return Response.Result; } } else //There is a response so return it. There could be an API error but that will be in the Response.Error object and the end user will see it. { if (Response.Result == null || (Response.Result.ProblemDetails != null && Response.Result.ProblemDetails.Status == "500")) { Message += "Response is null or API Error.TypeCode 3 Error, executing failover to swsbackup.serviceobjects.com;"; Response = HttpGet($"https://swsbackup.serviceobjects.com/PVI/GetPhoneDetails?{parameters}"); if (Response == null) //No Response returned from service, throw new exception. { Message += "Response is null on failover API call to swsbackup.serviceobjects.com; Check network access to Service Objects endpoints."; throw new Exception(Message); } else //There is a response so return it. There could be an API error but that will be in the Response.Error object and the end user will see it. { if (Response.Result == null) { Message += "Response is null on failover API call to swsbackup.serviceobjects.com; Check network access to Service Objects endpoints."; throw new Exception(Message); } if (Response.Result.ProblemDetails != null && Response.Result.ProblemDetails.Status == "500") { Message += "Response was 500 on failover API call to swsbackup.serviceobjects.com; Check network access to Service Objects endpoints."; throw new Exception(Message); } return Response.Result; } } return Response.Result; } } private static async Task<PVIResponse> HttpGet(string requestUrl) { ServicePointManager.SecurityProtocol = SecurityProtocolType.Ssl3 | SecurityProtocolType.Tls | SecurityProtocolType.Tls11 | SecurityProtocolType.Tls12; ServicePointManager.ServerCertificateValidationCallback += (sender, cert, chain, sslPolicyErrors) => true; HttpClient client = new HttpClient(); var task = Task.Run(() => client.GetAsync(requestUrl)); task.Wait(); HttpResponseMessage response = task.Result; HttpContent content = response.Content; string result = content.ReadAsStringAsync().Result; PVIResponse pVI = new PVIResponse(); if (response.StatusCode == HttpStatusCode.OK) { pVI.PhoneDetailsResponse = JsonConvert.DeserializeObject<PhoneDetailsResponse>(result); return pVI; } else { pVI.ProblemDetails = JsonConvert.DeserializeObject<ProblemDetails>(result); return pVI; } }
public static PVIResponse GetPhoneDetails(string Phone, string Country, string Options, string AuthID)
{

	//UrlEncode the values that will be sent to the API so that special characters don't break the url like "#" (Which can often be found in addresses where units are involved.)
	string Phone = HttpUtility.UrlEncode(Phone);
	string Country = HttpUtility.UrlEncode(Country);
	string Options = HttpUtility.UrlEncode(Options);
	string AuthID = HttpUtility.UrlEncode(AuthID);
	

	//Not using try/catch here because and errors here should bubble up to the calling code and will allow them to see the details of the thrown exception.
	Task<PVIResponse> Response = null;
	string Message = "";
	string parameters = $"Phone={Phone}&Country={Country}&Options={Options}&AuthID={AuthID}";

	Response = HttpGet($"https://sws.serviceobjects.com/PVI/GetPhoneDetails?{parameters}");
	if (Response == null) //Failover condition, typecode 3 is Service Objects Fatal
	{
		Message += "Response is null or API Error.TypeCode 3 Error, executing failover to swsbackup.serviceobjects.com;";
		Response = HttpGet($"https://swsbackup.serviceobjects.com/PVI/GetPhoneDetails?{parameters}");
		if (Response == null) //No Response returned from service, throw new exception.
		{
			Message += "Response is null on failover API call to swsbackup.serviceobjects.com; Check network access to Service Objects endpoints.";
			throw new Exception(Message);
		}
		else //There is a response so return it.  There could be an API error but that will be in the Response.Error object and the end user will see it.
		{
			if (Response.Result == null)
			{
				Message += "Response is null on failover API call to swsbackup.serviceobjects.com; Check network access to Service Objects endpoints.";
				throw new Exception(Message);

			}
			if (Response.Result.ProblemDetails != null && Response.Result.ProblemDetails.Status == "500")
			{
				Message += "Response was 500 on failover API call to swsbackup.serviceobjects.com; Check network access to Service Objects endpoints.";
				throw new Exception(Message);
			}

			return Response.Result;

		}
	}
	else //There is a response so return it.  There could be an API error but that will be in the Response.Error object and the end user will see it.
	{
		if (Response.Result == null || (Response.Result.ProblemDetails != null && Response.Result.ProblemDetails.Status == "500"))
		{
			Message += "Response is null or API Error.TypeCode 3 Error, executing failover to swsbackup.serviceobjects.com;";
			Response = HttpGet($"https://swsbackup.serviceobjects.com/PVI/GetPhoneDetails?{parameters}");
			if (Response == null) //No Response returned from service, throw new exception.
			{
				Message += "Response is null on failover API call to swsbackup.serviceobjects.com; Check network access to Service Objects endpoints.";
				throw new Exception(Message);
			}
			else //There is a response so return it.  There could be an API error but that will be in the Response.Error object and the end user will see it.
			{
				if (Response.Result == null)
				{
					Message += "Response is null on failover API call to swsbackup.serviceobjects.com; Check network access to Service Objects endpoints.";
					throw new Exception(Message);
				}
				if (Response.Result.ProblemDetails != null && Response.Result.ProblemDetails.Status == "500")
				{
					Message += "Response was 500 on failover API call to swsbackup.serviceobjects.com; Check network access to Service Objects endpoints.";
					throw new Exception(Message);
				}
				return Response.Result;
			}
		}
		return Response.Result;
	}
}

private static async Task<PVIResponse> HttpGet(string requestUrl)
{
	ServicePointManager.SecurityProtocol = SecurityProtocolType.Ssl3 | SecurityProtocolType.Tls | SecurityProtocolType.Tls11 | SecurityProtocolType.Tls12;
	ServicePointManager.ServerCertificateValidationCallback += (sender, cert, chain, sslPolicyErrors) => true;
	HttpClient client = new HttpClient();
	var task = Task.Run(() => client.GetAsync(requestUrl));
	task.Wait();
	HttpResponseMessage response = task.Result;
	HttpContent content = response.Content;
	string result = content.ReadAsStringAsync().Result;
	PVIResponse pVI = new PVIResponse();
	if (response.StatusCode == HttpStatusCode.OK)
	{
		pVI.PhoneDetailsResponse = JsonConvert.DeserializeObject<PhoneDetailsResponse>(result);
		return pVI;
	}
	else
	{
		pVI.ProblemDetails = JsonConvert.DeserializeObject<ProblemDetails>(result);
		return pVI;
	}
}

Phone Validation International C# Response Object

Plain text
Copy to clipboard
Open code in new window
EnlighterJS 3 Syntax Highlighter
using System.Collections.Generic;
using Newtonsoft.Json;
namespace DOTSPhoneValidationInternational
{
public class PVIResponse
{
public PhoneDetails PhoneDetailsResponse { get; set; }
public Problem ProblemDetails { get; set; }
}
public class PhoneDetails
{
[JsonProperty("score")]
public string Score { get; set; }
[JsonProperty("phoneIn")]
public string PhoneIn { get; set; }
[JsonProperty("countryCode")]
public int? CountryCode { get; set; }
[JsonProperty("formatNational")]
public string FormatNational { get; set; }
[JsonProperty("formatInternational")]
public string FormatInternational { get; set; }
[JsonProperty("formatE164")]
public string FormatE164 { get; set; }
[JsonProperty("extension")]
public string Extension { get; set; }
[JsonProperty("locality")]
public string Locality { get; set; }
[JsonProperty("adminArea")]
public string AdminArea { get; set; }
[JsonProperty("adminAreaAbbr")]
public string AdminAreaAbbr { get; set; }
[JsonProperty("country")]
public string Country { get; set; }
[JsonProperty("countryISO2")]
public string CountryISO2 { get; set; }
[JsonProperty("countryISO3")]
public string CountryISO3 { get; set; }
[JsonProperty("latitude")]
public double? Latitude { get; set; }
[JsonProperty("longitude")]
public double? Longitude { get; set; }
[JsonProperty("latLongMatchLevel")]
public string LatLongMatchLevel { get; set; }
[JsonProperty("timeZones")]
public List<TimeZone> TimeZones { get; set; }
[JsonProperty("lineType")]
public string LineType { get; set; }
[JsonProperty("smsAddress")]
public string SmsAddress { get; set; }
[JsonProperty("validPhone")]
public bool? ValidPhone { get; set; }
[JsonProperty("validPhoneLength")]
public bool? ValidPhoneLength { get; set; }
[JsonProperty("notes")]
public List<string> Notes { get; set; }
[JsonProperty("warnings")]
public List<string> Warnings { get; set; }
[JsonProperty("currentProvider")]
public ServiceProvider CurrentProvider { get; set; }
[JsonProperty("previousProvider")]
public ServiceProvider PreviousProvider { get; set; }
[JsonProperty("originalProvider")]
public ServiceProvider OriginalProvider { get; set; }
[JsonProperty("lastPortedDate")]
public string LastPortedDate { get; set; }
}
public class Problem
{
public string Type { get; set; }
public string Title { get; set; }
public string Status { get; set; }
public string Detail { get; set; }
}
public class TimeZone
{
public string ZoneName { get; set; }
public string ZoneAbbr { get; set; }
public string CountryISO3 { get; set; }
public string UtcOffset { get; set; }
}
public class ServiceProvider
{
public string ProviderID { get; set; }
public string ProviderName { get; set; }
public string CountryISO3 { get; set; }
}
}
using System.Collections.Generic; using Newtonsoft.Json; namespace DOTSPhoneValidationInternational { public class PVIResponse { public PhoneDetails PhoneDetailsResponse { get; set; } public Problem ProblemDetails { get; set; } } public class PhoneDetails { [JsonProperty("score")] public string Score { get; set; } [JsonProperty("phoneIn")] public string PhoneIn { get; set; } [JsonProperty("countryCode")] public int? CountryCode { get; set; } [JsonProperty("formatNational")] public string FormatNational { get; set; } [JsonProperty("formatInternational")] public string FormatInternational { get; set; } [JsonProperty("formatE164")] public string FormatE164 { get; set; } [JsonProperty("extension")] public string Extension { get; set; } [JsonProperty("locality")] public string Locality { get; set; } [JsonProperty("adminArea")] public string AdminArea { get; set; } [JsonProperty("adminAreaAbbr")] public string AdminAreaAbbr { get; set; } [JsonProperty("country")] public string Country { get; set; } [JsonProperty("countryISO2")] public string CountryISO2 { get; set; } [JsonProperty("countryISO3")] public string CountryISO3 { get; set; } [JsonProperty("latitude")] public double? Latitude { get; set; } [JsonProperty("longitude")] public double? Longitude { get; set; } [JsonProperty("latLongMatchLevel")] public string LatLongMatchLevel { get; set; } [JsonProperty("timeZones")] public List<TimeZone> TimeZones { get; set; } [JsonProperty("lineType")] public string LineType { get; set; } [JsonProperty("smsAddress")] public string SmsAddress { get; set; } [JsonProperty("validPhone")] public bool? ValidPhone { get; set; } [JsonProperty("validPhoneLength")] public bool? ValidPhoneLength { get; set; } [JsonProperty("notes")] public List<string> Notes { get; set; } [JsonProperty("warnings")] public List<string> Warnings { get; set; } [JsonProperty("currentProvider")] public ServiceProvider CurrentProvider { get; set; } [JsonProperty("previousProvider")] public ServiceProvider PreviousProvider { get; set; } [JsonProperty("originalProvider")] public ServiceProvider OriginalProvider { get; set; } [JsonProperty("lastPortedDate")] public string LastPortedDate { get; set; } } public class Problem { public string Type { get; set; } public string Title { get; set; } public string Status { get; set; } public string Detail { get; set; } } public class TimeZone { public string ZoneName { get; set; } public string ZoneAbbr { get; set; } public string CountryISO3 { get; set; } public string UtcOffset { get; set; } } public class ServiceProvider { public string ProviderID { get; set; } public string ProviderName { get; set; } public string CountryISO3 { get; set; } } }
using System.Collections.Generic;
using Newtonsoft.Json;


namespace DOTSPhoneValidationInternational
{
    public class PVIResponse
    {
        public PhoneDetails PhoneDetailsResponse { get; set; }
        public Problem ProblemDetails { get; set; }
    }

    public class PhoneDetails
    {
        [JsonProperty("score")]
        public string Score { get; set; }

        [JsonProperty("phoneIn")]
        public string PhoneIn { get; set; }

        [JsonProperty("countryCode")]
        public int? CountryCode { get; set; }

        [JsonProperty("formatNational")]
        public string FormatNational { get; set; }

        [JsonProperty("formatInternational")]
        public string FormatInternational { get; set; }

        [JsonProperty("formatE164")]
        public string FormatE164 { get; set; }

        [JsonProperty("extension")]
        public string Extension { get; set; }

        [JsonProperty("locality")]
        public string Locality { get; set; }

        [JsonProperty("adminArea")]
        public string AdminArea { get; set; }

        [JsonProperty("adminAreaAbbr")]
        public string AdminAreaAbbr { get; set; }

        [JsonProperty("country")]
        public string Country { get; set; }

        [JsonProperty("countryISO2")]
        public string CountryISO2 { get; set; }

        [JsonProperty("countryISO3")]
        public string CountryISO3 { get; set; }

        [JsonProperty("latitude")]
        public double? Latitude { get; set; }

        [JsonProperty("longitude")]
        public double? Longitude { get; set; }

        [JsonProperty("latLongMatchLevel")]
        public string LatLongMatchLevel { get; set; }

        [JsonProperty("timeZones")]
        public List<TimeZone> TimeZones { get; set; }

        [JsonProperty("lineType")]
        public string LineType { get; set; }

        [JsonProperty("smsAddress")]
        public string SmsAddress { get; set; }

        [JsonProperty("validPhone")]
        public bool? ValidPhone { get; set; }

        [JsonProperty("validPhoneLength")]
        public bool? ValidPhoneLength { get; set; }

        [JsonProperty("notes")]
        public List<string> Notes { get; set; }

        [JsonProperty("warnings")]
        public List<string> Warnings { get; set; }

        [JsonProperty("currentProvider")]
        public ServiceProvider CurrentProvider { get; set; }

        [JsonProperty("previousProvider")]
        public ServiceProvider PreviousProvider { get; set; }

        [JsonProperty("originalProvider")]
        public ServiceProvider OriginalProvider { get; set; }

        [JsonProperty("lastPortedDate")]
        public string LastPortedDate { get; set; }
    }

    public class Problem
    {
        public string Type { get; set; }
        public string Title { get; set; }
        public string Status { get; set; }
        public string Detail { get; set; }
    }

    public class TimeZone
    {
        public string ZoneName { get; set; }
        public string ZoneAbbr { get; set; }
        public string CountryISO3 { get; set; }
        public string UtcOffset { get; set; }
    }

    public class ServiceProvider
    {
        public string ProviderID { get; set; }
        public string ProviderName { get; set; }
        public string CountryISO3 { get; set; }
    }
}

Phone Validation International Java Rest Code Snippet

Plain text
Copy to clipboard
Open code in new window
EnlighterJS 3 Syntax Highlighter
String phone = "";
String country = "";
String options = "";
try {
//Pull in method arguements and encode the values for the call to the service
phone = URLEncoder.encode(Phone, "UTF-8").replaceAll("\\+", "%20");
country = URLEncoder.encode(Country, "UTF-8").replaceAll("\\+", "%20");
options = URLEncoder.encode(Options, "UTF-8").replaceAll("\\+", "%20");
} catch (UnsupportedEncodingException e) {
}
String QueryStringParameters = "Phone=" + phone + "&Country=" + country + "&Options=" + options + "&AuthID=" + AuthID;
String Message = "";
StringBuilder RawResponse = new StringBuilder();
PVI_Response.PD_Response Response = null;
RawResponse = HttpGet(mainUrl + QueryStringParameters);
Response = (PVI_Response.PD_Response)(ProcessResponse(RawResponse, "PD_Response"));
if (Response == null) //Failover condition, typecode 3 is Service Objects Fatal
{
Message += "Response is null or API Error.TypeCode 3 Error, executing failover to swsbackup.serviceobjects.com;";
RawResponse = HttpGet(backupUrl + QueryStringParameters);
Response = (PVI_Response.PD_Response)(ProcessResponse(RawResponse, "PD_Response"));
if (Response == null) //No Response returned from service, throw new exception.
{
Message += "Response is null on failover API call to swsbackup.serviceobjects.com; Check network access to Service Objects endpoints.";
throw new Exception(Message);
}
else //There is a response so return it. There could be an API error but that will be in the Response.Error object and the end user will see it.
{
if(Response.StatusDescription == null) {
Response.setStatusDescription("200");
}
return Response;
}
}
else {
if(Response.StatusDescription == null) {
Response.setStatusDescription("200");
}
return Response;
}
/**
* Returns a BestMatchesResponse object based on the input JSON string
* @param RawResponse Is a JSON string.
* @param ResponseType Is the string type of response object to cast to.
* @return Object Is the strongly typed response object for this service.
*/
private Object ProcessResponse(StringBuilder RawResponse, String ResponseType) throws Exception {
Gson gson = new Gson();
Object result = null;
switch(ResponseType) {
case "PD_Response":
result = gson.fromJson(RawResponse.toString(), PVI_Response.PD_Response.class);
if(result == null)
{
throw new Exception("ERROR: trying to get PVI_Response");
}
return result;
default:
throw new Exception("ERROR: trying to get PVI_Response");
}
}
/**
* Makes the call to an endpoint and returns a string representation of the response from the service.
* @param endpoint Is the URL API endpoint of the service operation.
* @return StringBuilder Is the string representation of the response from the service.
*/
private StringBuilder HttpGet(String endpoint) {
int timeout = 5000;
URL url = null;
HttpsURLConnection conn = null;
StringBuilder sb = new StringBuilder();
try {
url = new URL(endpoint);
/* System.out.println(url); */
conn = (HttpsURLConnection) url.openConnection();
conn.setConnectTimeout(timeout);
conn.setRequestMethod("GET");
conn.setRequestProperty("Accept", "application/json");
if (conn.getResponseCode() != 200) {
throw new RuntimeException("Failed : HTTP error code : " + conn.getResponseCode());
}
BufferedReader br = new BufferedReader(new InputStreamReader((conn.getInputStream())));
String output;
// System.out.println("info from the server \n");
while ((output = br.readLine()) != null) {
sb.append(output);
//System.out.println(output);
}
return sb;
} catch (Exception ex) {
System.out.println(ex.getMessage());
ex.printStackTrace();
}
finally {
if (conn != null)
conn.disconnect();
}
return sb;
}
String phone = ""; String country = ""; String options = ""; String mainUrl = "https://sws.serviceobjects.com/PVI/GetPhoneDetails?"; String backupUrl = "https://swsbackup.serviceobjects.com/PVI/GetPhoneDetails?"; String trialUrl = "https://trial.serviceobjects.com/PVI/GetPhoneDetails?"; try { //Pull in method arguements and encode the values for the call to the service phone = URLEncoder.encode(Phone, "UTF-8").replaceAll("\\+", "%20"); country = URLEncoder.encode(Country, "UTF-8").replaceAll("\\+", "%20"); options = URLEncoder.encode(Options, "UTF-8").replaceAll("\\+", "%20"); } catch (UnsupportedEncodingException e) { } String QueryStringParameters = "Phone=" + phone + "&Country=" + country + "&Options=" + options + "&AuthID=" + AuthID; String Message = ""; StringBuilder RawResponse = new StringBuilder(); PVI_Response.PD_Response Response = null; RawResponse = HttpGet(mainUrl + QueryStringParameters); Response = (PVI_Response.PD_Response)(ProcessResponse(RawResponse, "PD_Response")); if (Response == null) //Failover condition, typecode 3 is Service Objects Fatal { Message += "Response is null or API Error.TypeCode 3 Error, executing failover to swsbackup.serviceobjects.com;"; RawResponse = HttpGet(backupUrl + QueryStringParameters); Response = (PVI_Response.PD_Response)(ProcessResponse(RawResponse, "PD_Response")); if (Response == null) //No Response returned from service, throw new exception. { Message += "Response is null on failover API call to swsbackup.serviceobjects.com; Check network access to Service Objects endpoints."; throw new Exception(Message); } else //There is a response so return it. There could be an API error but that will be in the Response.Error object and the end user will see it. { if(Response.StatusDescription == null) { Response.setStatusDescription("200"); } return Response; } } else { if(Response.StatusDescription == null) { Response.setStatusDescription("200"); } return Response; } /** * Returns a BestMatchesResponse object based on the input JSON string * @param RawResponse Is a JSON string. * @param ResponseType Is the string type of response object to cast to. * @return Object Is the strongly typed response object for this service. */ private Object ProcessResponse(StringBuilder RawResponse, String ResponseType) throws Exception { Gson gson = new Gson(); Object result = null; switch(ResponseType) { case "PD_Response": result = gson.fromJson(RawResponse.toString(), PVI_Response.PD_Response.class); if(result == null) { throw new Exception("ERROR: trying to get PVI_Response"); } return result; default: throw new Exception("ERROR: trying to get PVI_Response"); } } /** * Makes the call to an endpoint and returns a string representation of the response from the service. * @param endpoint Is the URL API endpoint of the service operation. * @return StringBuilder Is the string representation of the response from the service. */ private StringBuilder HttpGet(String endpoint) { int timeout = 5000; URL url = null; HttpsURLConnection conn = null; StringBuilder sb = new StringBuilder(); try { url = new URL(endpoint); /* System.out.println(url); */ conn = (HttpsURLConnection) url.openConnection(); conn.setConnectTimeout(timeout); conn.setRequestMethod("GET"); conn.setRequestProperty("Accept", "application/json"); if (conn.getResponseCode() != 200) { throw new RuntimeException("Failed : HTTP error code : " + conn.getResponseCode()); } BufferedReader br = new BufferedReader(new InputStreamReader((conn.getInputStream()))); String output; // System.out.println("info from the server \n"); while ((output = br.readLine()) != null) { sb.append(output); //System.out.println(output); } return sb; } catch (Exception ex) { System.out.println(ex.getMessage()); ex.printStackTrace(); } finally { if (conn != null) conn.disconnect(); } return sb; }
String phone = "";
String country = "";
String options = "";

String mainUrl = "https://sws.serviceobjects.com/PVI/GetPhoneDetails?";
String backupUrl = "https://swsbackup.serviceobjects.com/PVI/GetPhoneDetails?";
String trialUrl = "https://trial.serviceobjects.com/PVI/GetPhoneDetails?";

try {
	//Pull in method arguements and encode the values for the call to the service
	phone = URLEncoder.encode(Phone, "UTF-8").replaceAll("\\+", "%20");
	country = URLEncoder.encode(Country, "UTF-8").replaceAll("\\+", "%20");
	options = URLEncoder.encode(Options, "UTF-8").replaceAll("\\+", "%20");

} catch (UnsupportedEncodingException e) {

}

String QueryStringParameters = "Phone=" + phone + "&Country=" + country + "&Options=" + options + "&AuthID=" + AuthID;
String Message = "";
StringBuilder RawResponse = new StringBuilder();
PVI_Response.PD_Response Response = null;

RawResponse = HttpGet(mainUrl + QueryStringParameters);
Response = (PVI_Response.PD_Response)(ProcessResponse(RawResponse, "PD_Response"));
if (Response == null) //Failover condition, typecode 3 is Service Objects Fatal
{
	Message += "Response is null or API Error.TypeCode 3 Error, executing failover to swsbackup.serviceobjects.com;";
	RawResponse = HttpGet(backupUrl + QueryStringParameters);
	Response = (PVI_Response.PD_Response)(ProcessResponse(RawResponse, "PD_Response"));
	if (Response == null) //No Response returned from service, throw new exception.
	{
		Message += "Response is null on failover API call to swsbackup.serviceobjects.com; Check network access to Service Objects endpoints.";
		throw new Exception(Message);
	}
	else //There is a response so return it.  There could be an API error but that will be in the Response.Error object and the end user will see it.
	{
		if(Response.StatusDescription == null) {
			Response.setStatusDescription("200");
		}
		return Response;
	}
}
else {
	if(Response.StatusDescription == null) {
		Response.setStatusDescription("200");
	}
	return Response;
}

/**
	* Returns a BestMatchesResponse object based on the input JSON string
	* @param RawResponse Is a JSON string.
	* @param ResponseType Is the string type of response object to cast to.
	* @return Object Is the strongly typed response object for this service.
*/
private Object ProcessResponse(StringBuilder RawResponse, String ResponseType) throws Exception {
	Gson gson = new Gson();
	Object result = null;
	switch(ResponseType) {
		case "PD_Response":
			result = gson.fromJson(RawResponse.toString(), PVI_Response.PD_Response.class);
			if(result == null)
			{ 
				throw new Exception("ERROR: trying to get PVI_Response");
			}
			return result;
		default:
			throw new Exception("ERROR: trying to get PVI_Response");
	}
}

/**
   * Makes the call to an endpoint and returns a string representation of the response from the service.
   * @param endpoint Is the URL API endpoint of the service operation.
   * @return StringBuilder Is the string representation of the response from the service.
*/
private StringBuilder HttpGet(String endpoint) {
	
	int timeout = 5000;
	URL url = null;
	HttpsURLConnection conn = null;
	StringBuilder sb = new StringBuilder();
	try {
		
		url = new URL(endpoint);

		/* System.out.println(url); */

		conn = (HttpsURLConnection) url.openConnection();

		conn.setConnectTimeout(timeout);
		conn.setRequestMethod("GET");
		conn.setRequestProperty("Accept", "application/json");

		if (conn.getResponseCode() != 200) {
			throw new RuntimeException("Failed : HTTP error code : " + conn.getResponseCode());
		}

		BufferedReader br = new BufferedReader(new InputStreamReader((conn.getInputStream())));
		
		String output;
		// System.out.println("info from the server \n");
		while ((output = br.readLine()) != null) {
			sb.append(output);
			//System.out.println(output);
		}
		return sb;
	} catch (Exception ex) {

		System.out.println(ex.getMessage());
		ex.printStackTrace();
	}
	finally {
		if (conn != null)
			conn.disconnect();
	}
	return sb;
}

Phone Validation International Java Response Object

Plain text
Copy to clipboard
Open code in new window
EnlighterJS 3 Syntax Highlighter
import java.util.List;
import com.google.gson.Gson;
import com.google.gson.GsonBuilder;
import com.google.gson.annotations.SerializedName;
public class PVI_Response {
public PVI_Response() {}
public class PD_Response {
/**
* PD_Response constructor
*/
public PD_Response() {}
@SerializedName("score")
public String score;
@SerializedName("phoneIn")
public String phoneIn;
@SerializedName("countryCode")
public Integer countryCode;
@SerializedName("formatNational")
public String formatNational;
@SerializedName("formatInternational")
public String formatInternational;
@SerializedName("formatE164")
public String formatE164;
@SerializedName("extension")
public String extension;
@SerializedName("locality")
public String locality;
@SerializedName("adminArea")
public String adminArea;
@SerializedName("adminAreaAbbr")
public String adminAreaAbbr;
@SerializedName("country")
public String country;
@SerializedName("countryISO2")
public String countryISO2;
@SerializedName("countryISO3")
public String countryISO3;
@SerializedName("latitude")
public Double latitude;
@SerializedName("longitude")
public Double longitude;
@SerializedName("latLongMatchLevel")
public String latLongMatchLevel;
@SerializedName("timeZones")
public List<TimeZone> timeZones;
@SerializedName("lineType")
public String lineType;
@SerializedName("smsAddress")
public String smsAddress;
@SerializedName("validPhone")
public Boolean validPhone;
@SerializedName("validPhoneLength")
public Boolean validPhoneLength;
@SerializedName("notes")
public List<String> notes;
@SerializedName("warnings")
public List<String> warnings;
@SerializedName("currentProvider")
public PhoneServiceProvider currentProvider;
@SerializedName("previousProvider")
public PhoneServiceProvider previousProvider;
@SerializedName("originalProvider")
public PhoneServiceProvider originalProvider;
@SerializedName("lastPortedDate")
public java.util.Date lastPortedDate;
@SerializedName("type")
public String type;
@SerializedName("title")
public String title;
@SerializedName("status")
public String StatusDescription;
@SerializedName("detail")
public String detail;
// Setter
public void setStatusDescription(String NewStatusDescription) {
this.StatusDescription = NewStatusDescription;
}
// Getters and Setters go here
// Nested classes
public class TimeZone {
public TimeZone() {}
public String zoneName;
public String zoneAbbr;
public String countryISO3;
public String utcOffset;
// Getters and Setters go here
}
public class PhoneServiceProvider {
public PhoneServiceProvider() {}
public String providerID;
public String providerName;
public String countryISO3;
// Getters and Setters go here
}
public class ProblemDetailsResponse {
public ProblemDetailsResponse() {}
@SerializedName("type")
public String type;
@SerializedName("title")
public String title;
@SerializedName("status")
public Integer status;
@SerializedName("detail")
public String detail;
}
/**Override of toString for end users to get quick output.*/
@Override
public String toString() {
Gson gson = new GsonBuilder().serializeNulls().create();
return gson.toJson(this);
}
}
}
import java.util.List; import com.google.gson.Gson; import com.google.gson.GsonBuilder; import com.google.gson.annotations.SerializedName; public class PVI_Response { public PVI_Response() {} public class PD_Response { /** * PD_Response constructor */ public PD_Response() {} @SerializedName("score") public String score; @SerializedName("phoneIn") public String phoneIn; @SerializedName("countryCode") public Integer countryCode; @SerializedName("formatNational") public String formatNational; @SerializedName("formatInternational") public String formatInternational; @SerializedName("formatE164") public String formatE164; @SerializedName("extension") public String extension; @SerializedName("locality") public String locality; @SerializedName("adminArea") public String adminArea; @SerializedName("adminAreaAbbr") public String adminAreaAbbr; @SerializedName("country") public String country; @SerializedName("countryISO2") public String countryISO2; @SerializedName("countryISO3") public String countryISO3; @SerializedName("latitude") public Double latitude; @SerializedName("longitude") public Double longitude; @SerializedName("latLongMatchLevel") public String latLongMatchLevel; @SerializedName("timeZones") public List<TimeZone> timeZones; @SerializedName("lineType") public String lineType; @SerializedName("smsAddress") public String smsAddress; @SerializedName("validPhone") public Boolean validPhone; @SerializedName("validPhoneLength") public Boolean validPhoneLength; @SerializedName("notes") public List<String> notes; @SerializedName("warnings") public List<String> warnings; @SerializedName("currentProvider") public PhoneServiceProvider currentProvider; @SerializedName("previousProvider") public PhoneServiceProvider previousProvider; @SerializedName("originalProvider") public PhoneServiceProvider originalProvider; @SerializedName("lastPortedDate") public java.util.Date lastPortedDate; @SerializedName("type") public String type; @SerializedName("title") public String title; @SerializedName("status") public String StatusDescription; @SerializedName("detail") public String detail; // Setter public void setStatusDescription(String NewStatusDescription) { this.StatusDescription = NewStatusDescription; } // Getters and Setters go here // Nested classes public class TimeZone { public TimeZone() {} public String zoneName; public String zoneAbbr; public String countryISO3; public String utcOffset; // Getters and Setters go here } public class PhoneServiceProvider { public PhoneServiceProvider() {} public String providerID; public String providerName; public String countryISO3; // Getters and Setters go here } public class ProblemDetailsResponse { public ProblemDetailsResponse() {} @SerializedName("type") public String type; @SerializedName("title") public String title; @SerializedName("status") public Integer status; @SerializedName("detail") public String detail; } /**Override of toString for end users to get quick output.*/ @Override public String toString() { Gson gson = new GsonBuilder().serializeNulls().create(); return gson.toJson(this); } } }
import java.util.List;
import com.google.gson.Gson;
import com.google.gson.GsonBuilder;
import com.google.gson.annotations.SerializedName;

public class PVI_Response {
	
	public PVI_Response() {}

	public class PD_Response {
		
		/**
		   * PD_Response constructor
		*/
		public PD_Response() {}

		@SerializedName("score")
		public String score;
		
		@SerializedName("phoneIn")
		public String phoneIn;
		
		@SerializedName("countryCode")
	    public Integer countryCode;
		
		@SerializedName("formatNational")
	    public String formatNational;
		
		@SerializedName("formatInternational")
	    public String formatInternational;
		
		@SerializedName("formatE164")
		public String formatE164;
		
		@SerializedName("extension")
		public String extension;
		
		@SerializedName("locality")
	    public String locality;
		
		@SerializedName("adminArea")
	    public String adminArea;
		
		@SerializedName("adminAreaAbbr")
	    public String adminAreaAbbr;
		
		@SerializedName("country")
	    public String country;
		
		@SerializedName("countryISO2")
	    public String countryISO2;
		
		@SerializedName("countryISO3")
	    public String countryISO3;
		
		@SerializedName("latitude")
	    public Double latitude;
		
		@SerializedName("longitude")
	    public Double longitude;
		
		@SerializedName("latLongMatchLevel")
	    public String latLongMatchLevel;
		
		@SerializedName("timeZones")
	    public List<TimeZone> timeZones;
		
		@SerializedName("lineType")
	    public String lineType;
		
		@SerializedName("smsAddress")
	    public String smsAddress;
		
		@SerializedName("validPhone")
	    public Boolean validPhone;
		
		@SerializedName("validPhoneLength")
	    public Boolean validPhoneLength;
		
		@SerializedName("notes")
	    public List<String> notes;
		
		@SerializedName("warnings")
	    public List<String> warnings;
		
		@SerializedName("currentProvider")
	    public PhoneServiceProvider currentProvider;
		
		@SerializedName("previousProvider")
	    public PhoneServiceProvider previousProvider;
		
		@SerializedName("originalProvider")
	    public PhoneServiceProvider originalProvider;
		
		@SerializedName("lastPortedDate")
	    public java.util.Date lastPortedDate;
		
		@SerializedName("type")
        public String type;

		@SerializedName("title")
        public String title;

		@SerializedName("status")
        public String StatusDescription;

		@SerializedName("detail")
        public String detail;
		
		// Setter
		public void setStatusDescription(String NewStatusDescription) {
		  this.StatusDescription = NewStatusDescription;
		}
		
	    // Getters and Setters go here

	    // Nested classes
	    public class TimeZone {
			public TimeZone() {}
	        public String zoneName;
	        public String zoneAbbr;
	        public String countryISO3;
	        public String utcOffset;

	        // Getters and Setters go here
	    }

	    public class PhoneServiceProvider {
			public PhoneServiceProvider() {}
	        public String providerID;
	        public String providerName;
	        public String countryISO3;

	        // Getters and Setters go here
	    }

	    public class ProblemDetailsResponse {
	    	
			public ProblemDetailsResponse() {}
	    	
			@SerializedName("type")
	        public String type;
			
			@SerializedName("title")
	        public String title;
			
			@SerializedName("status")
	        public Integer status;
	        
			@SerializedName("detail")
	        public String detail;

	    }
	    
		/**Override of toString for end users to get quick output.*/
		@Override
		public String toString() {
			Gson gson = new GsonBuilder().serializeNulls().create(); 
	        return gson.toJson(this);
	    }
	}
}