c# - http web request with https and basic authentication -
i'm trying webrequest on https url basic authentication. , not working! below code, works if use non secure url vs secure one, , can't figure out i'm doing wrong. works find non secure, when secure url used, 401 user auth error. set wrong on server, or code?
could me?
var req = system.net.httpwebrequest.create(url) httpwebrequest; req.method = method.tostring(); req.contenttype = "application/json"; req.date = requesttime; req.proxy = null; string credentials = string.format("{0}:{1}", "xxxx", "xxxx"); byte[] bytes = encoding.ascii.getbytes(credentials); string base64 = convert.tobase64string(bytes); string authorization = string.concat("basic ", base64); req.headers.add("authorization", authorization); httpwebresponse response = (httpwebresponse)req.getresponse(); stream receivestream = response.getresponsestream(); streamreader readstream = new streamreader(receivestream, encoding.utf8); string responsebody = readstream.readtoend(); console.writeline(responsebody); response.close(); readstream.close();
this works me:
var webrequest = (httpwebrequest)webrequest.create(url); webrequest.method = "get"; webrequest.contenttype = "application/json"; webrequest.useragent = "mozilla/5.0 (windows nt 5.1; rv:28.0) gecko/20100101 firefox/28.0"; webrequest.contentlength = 0; // added per comment string autorization = "username" + ":" + "password"; byte[] binaryauthorization = system.text.encoding.utf8.getbytes(autorization); autorization = convert.tobase64string(binaryauthorization); autorization = "basic " + autorization; webrequest.headers.add("authorization", autorization); var webresponse = (httpwebresponse)webrequest.getresponse(); if (webresponse.statuscode != httpstatuscode.ok) console.writeline("{0}",webresponse.headers); using (streamreader reader = new streamreader(webresponse.getresponsestream())) { string s = reader.readtoend(); console.writeline(s); reader.close(); }
Comments
Post a Comment