public ActionResult Index()
{
return View();
}
private class GoogleResponse
{
public string longUrl { get; set; }
}
[HttpPost]
public JsonResult GetShortURL(string longUrl)
{
WebRequest request = WebRequest.Create("https://www.googleapis.com/urlshortener/v1/url?key=AIzaSyDFhSDbTWk_dcit15wDWtIUG2CTfSM-nnM");
request.Method = "POST";
request.ContentType = "application/json";
string requestData = string.Format(@"{{""longUrl"": ""{0}""}}", longUrl);
byte[] requestRawData = Encoding.ASCII.GetBytes(requestData);
request.ContentLength = requestRawData.Length;
Stream requestStream = request.GetRequestStream();
requestStream.Write(requestRawData, 0, requestRawData.Length);
requestStream.Close();
WebResponse response = request.GetResponse();
StreamReader responseReader = new StreamReader(response.GetResponseStream());
string responseData = responseReader.ReadToEnd();
responseReader.Close();
var deserializer = new JavaScriptSerializer();
var results = deserializer.Deserialize(responseData);
return Json(results.Id);
}
}
}
------------------------------------------------------------------------
Index
$(document).ready(function () {
$("#button1").click(function () {
$.ajax({
type: "POST",
url: "/Home/GetShortURL",
contentType: "application/json;charset=utf-8",
dataType: "json",
data: '{ "longUrl" : "' + $("#text1").val() + '" }',
success: function (results) {
$("#text2").val(results);
Console.log("button1");
},
error: function (err) {
alert(err.status + " - " + err.statusText);
}
});
});
});
Enter Long URL :
This Code Convert Long Url To Short Url . But i will be face a problem(the remote server returned an error (403) forbidden) .. Please solve my error.
1 Reply
Know the answer? Post it — somebody with the same question will find it here.
Sign in to answer this question
It is the same account you read, post and publish with — and you will come straight back to this page.
Madan ShekarPosted Jul 3, 2019, 6:46 AM