Google URL Shortener API: Converting a long URL to short - short-url

I want to convert a long URL into short one.
I have followed the documentation, but I'm not able to convert the URL.
It's resulting in 403 response.
I followed below aproach.
JSONObject reqObj = new JSONObject();
reqObj.put("longUrl", LONG_URL_TO_CONVERT);
reqObj.put("key", API_KEY);
URL url = new URL("https://www.googleapis.com/urlshortener/v1/url");
HttpURLConnection conn = (HttpURLConnection) url.openConnection();
conn.setRequestProperty("Content-Type", "application/json");
conn.setRequestMethod("POST");
conn.setDoOutput(true);
OutputStream outputStream = conn.getOutputStream();
outputStream.write(reqObj.toString().getBytes());
InputStream inputStream = conn.getInputStream();
String resp = readStream(inputStream);
I tried with GET request
https://www.googleapis.com/urlshortener/v1/url?key=API_KEY&longUrl=www.google.com
but it's returning an error message Required parameter: shortUrl
What I'm doing wrong here ?

Finally found the solution.
Instead of adding key as a post param, appended it to the URL itself. like
https://www.googleapis.com/urlshortener/v1/url?key={API_KEY}
and it worked as expected.

Related

RestTemplate request with braces ("{", "}")

I want to send request through RestTemplate. But my url has braces ('{', '}'), and therefore I have exception: "Not enough variable values available to expand ...".
I try do it through uri
UriComponentsBuilder builder = UriComponentsBuilder.fromPath(url);
UriComponents uriComponents = builder.build();
URI uri = uriComponents.toUri();
But I got new exception:"protocol = https host = null".
How I can send request with my URL? In URL must be braces.
My code:
String url = "https://api.vk.com/method/execute?code=return[API.users.search({"count":1})];&access_token...
String result = restTemplate.getForObject(url, String.class);
Below code encrypts the uri using UriComponentsBuilder, adds query params using RestTemplate and also sets HttpHeaders if any.
public HttpEntity<String> getEntityByUri() {
String req = "https://api.vk.com/method/execute";
UriComponentsBuilder builder = UriComponentsBuilder.fromHttpUrl(req)
.queryParam("code",
"return[API.users.search({"count":1})]");
HttpHeaders headers = new HttpHeaders();
headers.setAccept(Arrays.asList(MediaType.ALL));
HttpEntity<String> httpEntity = new HttpEntity<String>(headers);
return new RestTemplate().exchange(builder.build().encode().toUri(), HttpMethod.GET, httpEntity, String.class);
}
Hope this helps and good luck!

MarkLogic spring RestTemplate

Hi I am trying to get the list of graphs in MarkLogic using RestTemplate.
Below is the sample code. From the browser I can able to get the graph list, but through the Java REST Client I am getting error 401.
HttpHeaders header = new HttpHeaders();
String plainCreds = "restadmin:restpassword";
byte[] plainCredsBytes = plainCreds.getBytes();
byte[] base64CredsBytes = Base64.encode(plainCredsBytes);
String base64Creds = new String(base64CredsBytes);
header.setAccessControlAllowCredentials(true);
header.add("Authorization", "Basic " + base64Creds);
header.setAccept(Arrays.asList(MediaType.TEXT_XML));
header.setContentType(MediaType.TEXT_XML);
HttpEntity<String> entity = new HttpEntity<String>(header);
String url = "http://localhost:8003/v1/graphs";
ResponseEntity response = restTemplate.exchange(url, HttpMethod.GET, entity, String.class);
System.out.println("Response : "+response.getStatusCode());
Please help me in resolving the issue
Try copying the HTTP auth code at https://github.com/rjrudin/ml-app-deployer/blob/master/src/main/java/com/rjrudin/marklogic/rest/util/RestTemplateUtil.java#L18 - I know it will handle HTTP basic auth against the management API on port 8002, and it should work fine on your REST API server on port 8003.

Getting Facebook Page Feed ( using graph api ) in asp.net, receiving error "Unsupported Browser"

I am trying to get facebook page feed ( public posts) which does not require any access token.
here's the url
https://www.facebook.com/feeds/page.php?format=json&id=1393547494231876
when i run this in browser where id= any facebook page id. it returns first 25 public posts in json format.
but when i run this in my code to get json result facebook return a page saying "unsupported browser"
this is my method . i pass it facebook page id to get posts..
public static String GetPosts(string PageId)
{
string id = PageId;
string apilink = "https://www.facebook.com/feeds/page.php?format=json&id=";
HttpWebRequest request = WebRequest.Create(apilink + id) as HttpWebRequest;
request.Method = WebRequestMethods.Http.Get;
request.Accept = "application/json";
request.ContentType = "application/json; charset=utf-8";
// Get response
using (HttpWebResponse response = request.GetResponse() as HttpWebResponse)
{
// Get the response stream
StreamReader reader = new StreamReader(response.GetResponseStream());
// Console application output
String result = reader.ReadToEnd();
return result;
}
}
Here's the result that i get in return string
Result Image String
and so on remaining page returned.
Can somebody help me how to get it working??
Update
Found Answer...
I Have To Set User agent to make Facebook think i am a browser..
so just added
request.UserAgent = ".NET Framework";
and i worked.
Thanks to All.
Found Answer... I Have To Set User agent to make Facebook think i am a browser.. so just added request.UserAgent = ".NET Framework"; and i worked. Thanks to All.

Stuck Streaming Xml

This is the code i have written to get the xml of one url but it says
"Data at the root level is invalid" with any url.. Can someone specify why?
XmlDocument xdoc = new XmlDocument();//xml doc used for xml parsing
xdoc.LoadXml("http://latestpackagingnews.blogspot.com/feeds/posts/default");//loading XML in xml doc
XmlNodeList xNodelst = xdoc.DocumentElement.SelectNodes("entry");//reading node so that we can traverse thorugh the XML
Response.Write(xNodelst);
You need to first download your xml data using WebClient class
string downloadedString;
System.Net.WebClient client = new System.Net.WebClient();
downloadedString = client.DownloadString("http://latestpackagingnews.blogspot.com/feeds/posts/default");
//Now write this string as an xml
//I think you can easily do it with XmlDocument class and then read it
The xdoc.LoadXml can not for read url, change it to xdoc.Load and it will work.
You can also read : Using Returned XML with C#
XmlDocument.LoadXml method awaits XML-text, but not the source URL.
First, download page content into string and then pass it to LoadXml. Here is how you can download:
public string GetUrlContent(string url)
{
var request = (HttpWebRequest)HttpWebRequest.Create(url);
var response = (HttpWebResponse)request.GetResponse();
var reader = new StreamReader(response.GetResponseStream(), Encoding.UTF8);
var content = reader.ReadToEnd();
reader.Close();
response.Close();
return content;
}
In your case it would be:
var content = GetUrlContent("http://latestpackagingnews.blogspot.com/feeds/posts/default");
var doc = new XmlDocument();
doc.LoadXml(content);

The remote server returned an error: (400) Bad Request while consuming a WCF Service

Please view the code given below. While the debug reaches the request.GetResponse() statement the error has been thrown.
Uri uri = new Uri(address);
string data = "<s:Envelope xmlns:s='http://schemas.xmlsoap.org/soap/envelope/'><s:Body><HasRole xmlns='http://tempuri.org/'><userName>" + sid + "</userName><role>" + role + "</role></HasRole></s:Body></s:Envelope>";
data.Replace("'", "\"");
// Create a byte array of the data we want to send
byte[] byteData = UTF8Encoding.UTF8.GetBytes(data);
if (uri.Scheme == Uri.UriSchemeHttps)
{
HttpWebRequest request = (HttpWebRequest)HttpWebRequest.Create(uri);
request.Method = "POST";// WebRequestMethods.Http.Post;
request.ContentLength = byteData.Length;
request.ContentType = "application/soap+xml; charset=UTF-8"; // "text/xml; charset=utf-8";
//request.ContentType = "application/x-www-form-urlencoded";
//Stream requestStream = request.GetRequestStream();
using (Stream writer = request.GetRequestStream())
{
writer.Write(byteData, 0, byteData.Length);
}
//writer.Close();
using (HttpWebResponse response = request.GetResponse() as HttpWebResponse)
{
// Get the response stream
StreamReader reader = new StreamReader(response.GetResponseStream());
string tmp = reader.ReadToEnd();
Response.Close();
Response.Write(tmp);
}
I would double check the URL. If the URL looks ok on the client side, I recommend looking at access logs on your server to see what URL is being hit. 4xx errors mean a resource was not found. If the endpoint was correct, but the request was fubared, you would get a 5xx error code. (Assuming that your server side frameworks uses standard HTTP Response Codes).
As has been mentioned you should use the 'Add Service Reference' to access the WCF service from a .NET client. However, if you're emulating trying to connect from a non .NET client, your soap envelope is missing the header information.
<s:Header>
<Action s:mustUnderstand="1" xmlns="http://schemas.microsoft.com/ws/2005/05/addressing/none">
specify your action namespace here (e.g. http://tempuri.org/ISomeService/Execute)
</Action>
</s:Header>

Resources