简体   繁体   中英

Google shortener url Invalid Value in java

i am facing a problem with google shortener url.

Here is my java code :

public static String shortenUrl(String longUrl)
{
    String GOOGLE_URL_SHORT_API = "https://www.googleapis.com/urlshortener/v1/url";
    String GOOGLE_API_KEY = MYAPIKEY;

    Logger.info("LONG URL IS ==> "+longUrl);

    String shortUrl="";


    if (longUrl == null) {
        Logger.info("LONGURL NULL");
        return longUrl;
    }else if(!longUrl.startsWith("http://") && !longUrl.startsWith("https://")){
        longUrl = "http://"+longUrl;
    }
    try {
        String json = "{\"longUrl\": \""+longUrl+"\"}";
        String apiURL = GOOGLE_URL_SHORT_API+"?key="+GOOGLE_API_KEY;


        HttpPost postRequest = new HttpPost(apiURL);
        postRequest.setHeader("Referer", "servizio.wiforwater.xom");
        postRequest.setHeader("Content-Type", "application/json");
        postRequest.setEntity(new StringEntity(json, "UTF-8"));


        CloseableHttpClient httpClient = HttpClients.createDefault();
        HttpResponse response = httpClient.execute(postRequest);
        String responseText = EntityUtils.toString(response.getEntity());
        Logger.info("responseText ==> "+responseText);
        Gson gson = new Gson();
        @SuppressWarnings("unchecked")
        HashMap<String, String> res = gson.fromJson(responseText, HashMap.class);
        String result = res.get("id");
        Logger.info("result is ==> "+result);
        return result;

    } catch (MalformedURLException e) {
        return "MalformedURLException error";
    } catch (IOException e) {
        return "IOException error";
    }


}

The output in my console is :

  [info] application - responseText ==> {
 "error": {
  "errors": [
   {
    "domain": "global",
    "reason": "invalid",
    "message": "Invalid Value",
    "locationType": "parameter",
    "location": "resource.longUrl"
   }
  ],
  "code": 400,
  "message": "Invalid Value"
 }
}

I have configured everything in my google console developers and searched everything possible on the internet.

Can someone tell me where i am doing wrong?

Thanks to all

One major problem you are facing is that you build the JSON request by string concatenation without proper JSON escaping:

String json = "{\\"longUrl\\": \\""+longUrl+"\\"}";

The common approach would be to use a JSON library, set all properties using the JSON library and in the end just retrieve the string representation that is properly escaped.

If you are not using a JSON library you should at least apply a JSON encoding/escaping on the longUrl before pasting it into the json string.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM