11using System ;
22using System . Collections ;
33using System . IO ;
4+ using System . Linq ;
45using JsonLD . Core ;
56using JsonLD . Util ;
7+ using System . Net ;
8+ using System . Collections . Generic ;
69
710namespace JsonLD . Core
811{
@@ -14,18 +17,52 @@ public virtual RemoteDocument LoadDocument(string url)
1417 RemoteDocument doc = new RemoteDocument ( url , null ) ;
1518 try
1619 {
17- doc . Document = JSONUtils . FromURL ( new Uri ( url ) ) ;
20+ HttpWebRequest req = ( HttpWebRequest ) HttpWebRequest . Create ( url ) ;
21+ req . Accept = AcceptHeader ;
22+ WebResponse resp = req . GetResponse ( ) ;
23+ bool isJsonld = resp . Headers [ HttpResponseHeader . ContentType ] == "application/ld+json" ;
24+ if ( ! resp . Headers [ HttpResponseHeader . ContentType ] . Contains ( "json" ) )
25+ {
26+ throw new JsonLdError ( JsonLdError . Error . LoadingDocumentFailed , url ) ;
27+ }
28+
29+ string [ ] linkHeaders = resp . Headers . GetValues ( "Link" ) ;
30+ if ( ! isJsonld && linkHeaders != null )
31+ {
32+ linkHeaders = linkHeaders . SelectMany ( ( h ) => h . Split ( "," . ToCharArray ( ) ) )
33+ . Select ( h => h . Trim ( ) ) . ToArray ( ) ;
34+ IEnumerable < string > linkedContexts = linkHeaders . Where ( v => v . EndsWith ( "rel=\" http://www.w3.org/ns/json-ld#context\" " ) ) ;
35+ if ( linkedContexts . Count ( ) > 1 )
36+ {
37+ throw new JsonLdError ( JsonLdError . Error . MultipleContextLinkHeaders ) ;
38+ }
39+ string header = linkedContexts . First ( ) ;
40+ string linkedUrl = header . Substring ( 1 , header . IndexOf ( ">" ) - 1 ) ;
41+ string resolvedUrl = URL . Resolve ( url , linkedUrl ) ;
42+ var remoteContext = this . LoadDocument ( resolvedUrl ) ;
43+ doc . contextUrl = remoteContext . documentUrl ;
44+ doc . context = remoteContext . document ;
45+ }
46+
47+ Stream stream = resp . GetResponseStream ( ) ;
48+
49+ doc . DocumentUrl = req . Address . ToString ( ) ;
50+ doc . Document = JSONUtils . FromInputStream ( stream ) ;
51+ }
52+ catch ( JsonLdError )
53+ {
54+ throw ;
1855 }
1956 catch ( Exception )
2057 {
21- throw new JsonLdError ( JsonLdError . Error . LoadingRemoteContextFailed , url ) ;
58+ throw new JsonLdError ( JsonLdError . Error . LoadingDocumentFailed , url ) ;
2259 }
2360 return doc ;
2461 }
2562
26- // /// <summary>An HTTP Accept header that prefers JSONLD.</summary>
27- // /// <remarks>An HTTP Accept header that prefers JSONLD.</remarks>
28- // public const string AcceptHeader = "application/ld+json, application/json;q=0.9, application/javascript;q=0.5, text/javascript;q=0.5, text/plain;q=0.2, */*;q=0.1";
63+ /// <summary>An HTTP Accept header that prefers JSONLD.</summary>
64+ /// <remarks>An HTTP Accept header that prefers JSONLD.</remarks>
65+ public const string AcceptHeader = "application/ld+json, application/json;q=0.9, application/javascript;q=0.5, text/javascript;q=0.5, text/plain;q=0.2, */*;q=0.1" ;
2966
3067// private static volatile IHttpClient httpClient;
3168
0 commit comments