I want to create a json payload like
{
"email":"dautpure#gmail.com",
"validators": ["SyntaxValidator", "MXValidator", "ListDetectiveValidator"]
}
I wrote the following code :
package com.forcelocker.loaddata;
import com.google.gson.JsonObject;
import com.mashape.unirest.http.HttpResponse;
import com.mashape.unirest.http.Unirest;
import com.mashape.unirest.http.exceptions.UnirestException;
import java.lang.reflect.Array;
import java.util.ArrayList;
public class validateEmail
{
public static String CheckingURL = "h_ttps://abc.com/address/v1/validateEmail";
private static final String Content_Type ="application/json";
public static Boolean CheckEmail(String Email,String Token) throws UnirestException
{
Boolean IsmailOk=false;
String Authorization = "Bearer "+Token;
JsonObject payload = new JsonObject();
payload.addProperty("email", Email);
HttpResponse<String> response = Unirest.post(CheckingURL)
.header("Content-Type", Content_Type)
.header("Authorization", Authorization)
.body(payload).asString();
return IsmailOk;
}
}
But I don't know how to put the validator in JSON which can hold a comma seperate values
any help would be great.
what about
payload.addProperty("validator", new String [] {"SyntaxValidator", "MXValidator", "ListDetectiveValidator"});
The problem was solved by using hashmap as suggested by noname. then converting it to json string and using it as payload for api
Map<String,Object> map = new HashMap<>();
String[] val = new String[] {"SyntaxValidator", "MXValidator", "ListDetectiveValidator"};
map.put("email", Email);
map.put("validators", val);
ObjectMapper objectMapper = new ObjectMapper();
String json = objectMapper.writeValueAsString(map);
Thanks noname
Related
From my understanding, if you return the following json string: {"headers":{"Content-Type":"application/json"},"body":"hello world","statusCode":200}
then when visiting the page https://....eu-west-2.amazonaws.com/prod/, you should see the phrase "hello world" written. Instead, I get {"message": "Internal server error"}
Below is the JAVA code I am using to return the above json string:
import com.amazonaws.services.lambda.runtime.Context;
import com.amazonaws.services.lambda.runtime.RequestHandler;
import org.json.simple.JSONObject;
import java.util.Map;
public class Handler implements RequestHandler<Map<String, String>, JSONObject>{
#Override
public JSONObject handleRequest(Map<String, String> stringStringMap, Context context) {
JSONObject obj = new JSONObject();
JSONObject obj2 = new JSONObject();
obj2.put("Content-Type", "application/json");
obj.put("statusCode", 200);
obj.put("headers", obj2);
obj.put("body", "hello world");
return obj;
}
}
What am I doing wrong? It works fine on the console when I test the function, but when I go to the page of the API it gives me an internal server error.
The error message you posted in the comment has already explained what the problem is. Basically, lambda handler is not able to convert the input object to String. You can solve this by changing Map<String, String> to Map<String, Object> or general Object.
Also, as #david pointed out in the comment, you should return a JSON String instead of a JSONObject. So the fully working code could be something like this:
import com.amazonaws.services.lambda.runtime.Context;
import com.amazonaws.services.lambda.runtime.RequestHandler;
import org.json.simple.JSONObject;
import java.util.Map;
public class Handler implements RequestHandler<Map<String, Object>, String>{
#Override
public String handleRequest(Map<String, Object> stringStringMap, Context context) {
JSONObject obj = new JSONObject();
JSONObject obj2 = new JSONObject();
obj2.put("Content-Type", "application/json");
obj.put("statusCode", 200);
obj.put("headers", obj2);
obj.put("body", "hello world");
return obj.toString();
}
}
For anyone interested, the following code worked fine for me:
import com.amazonaws.services.lambda.runtime.Context;
import com.amazonaws.services.lambda.runtime.RequestStreamHandler;
import org.json.simple.JSONObject;
import java.io.*;
public class Handler implements RequestStreamHandler{
#Override
public void handleRequest(InputStream inputStream, OutputStream outputStream,
Context context) throws IOException {
JSONObject obj = new JSONObject();
JSONObject obj2 = new JSONObject();
obj2.put("Content-Type", "application/json");
obj.put("statusCode", 200);
obj.put("headers", obj2);
obj.put("body", "hello world");
OutputStreamWriter writer = new OutputStreamWriter(outputStream, "UTF-8");
writer.write(obj.toString());
writer.close();
}
}
I'm trying to execute the following two requests using EBay's Inventory API:
POST: bulkUpdatePriceQuantity (create new listing)
PUT: createOrReplaceInventoryItem (update price/quantity of listing) using
I'm fairly new to Retrofit and OKHTTP and was wondering if someone could post a simple example of how to create a new listing and update price/quantity of an existing listing.
I've spent a couple of days reading about Retrofit and OKHTTP and it seems very confusing. Like I don't understand where/how to add the EBay authorization token and how to pass the data to EBay (such as the new price/quantity or the details of a new listing).
So far this is what I've come up with for Retrofit:
public interface RetrofitEBaySellAPIService {
#Headers("X-EBAY-C-PACKED-EXAMPLE: Authorization: Bearer <TOKEN_GOES_HERE>")
#POST("/bulk_update_price_quantity")
// https://api.ebay.com/sell/inventory/v1/bulk_update_price_quantity
Call<List<Task>> getTasks();
Retrofit retrofit = new Retrofit.Builder()
.baseUrl("https://api.ebay.com/sell/inventory/v1/")
.addConverterFactory(GsonConverterFactory.create()) // error: GsonConverterFactory cannot be resolved
.build();
RetrofitEBaySellAPIService service = retrofit.create(RetrofitEBaySellAPIService.class);
Response response = service.getClientList("").execute();
}
And this is what I've come up with for OKHTTP:
public class OKHTTPPostExample {
public OKHTTPPostExample()
{
}
public static final MediaType JSON
= MediaType.parse("application/json; charset=utf-8");
OkHttpClient client = new OkHttpClient();
public String post(String url, String json) throws IOException {
RequestBody body = RequestBody.create(JSON, json);
String header = "Authorization: Bearer <TOKEN_GOES_HERE?>";
Headers headerbuild = Headers.of(header);
Request request = new Request.Builder()
.url(url)
.post(body)
.headers(headerbuild)
.build();
try (Response response = client.newCall(request).execute()) {
return response.body().string();
}
}
public String revisePriceAndQuantity(String sku) {
return "{
'requests' : [
{
'sku' : 'SKU_STRING',
"shipToLocationAvailability" :
{
'quantity' : 'integer'
}";
}
}
However, in both cases I'm getting numerous errors. I've read about both technologies for hours (my head is spinning) but I do not understand it clearly.
If someone could post a simple example of how to do both of these operations I would greatly appreciate it.
Unfortunately I don't have developer account to check that it actually works but here is an example of bulkUpdatePriceQuantity
package example;
import java.io.IOException;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import retrofit2.Call;
import retrofit2.Retrofit;
import retrofit2.converter.gson.GsonConverterFactory;
import retrofit2.http.Body;
import retrofit2.http.HeaderMap;
import retrofit2.http.POST;
public class Runner {
//DTOs
public static class Offer {
public Integer availableQuantity;
public String offerId;
public Price price;
}
public static class ShipToLocationAvailability {
public Integer quantity;
}
public static class Price {
public String currency;
public String value;
}
public static class Request {
public List<Offer> offers = null;
public ShipToLocationAvailability shipToLocationAvailability;
public String sku;
}
public static class Response {
public String offerId;
public String sku;
public Integer statusCode;
}
public static class RequestBody{
public List<Request> requests;
}
public static class ResponseBody{
public List<Response> responses;
}
//api interface
public static interface RetrofitEBaySellAPIService {
#POST("/bulk_update_price_quantity")
Call<ResponseBody> bulkUpdatePriceQuantity(#HeaderMap Map<String, String> headers, #Body RequestBody object);
}
//entry point
public static void main(String[] args) throws IOException {
/**
* request should be initialized.
* you can do it by creating all necessary objects manually
* or by deserializing the object from json like this
* RequestBody request = new Gson().fromJson(jsonString, RequestBody.class);
*
* where jsonString is a string that contains json representation of your request body
*
*/
RequestBody request = null;
Retrofit retrofit = new Retrofit.Builder().baseUrl("https://api.ebay.com/sell/inventory/v1/")
.addConverterFactory(GsonConverterFactory.create())
.build();
RetrofitEBaySellAPIService service = retrofit.create(RetrofitEBaySellAPIService.class);
Map<String, String> headers = new HashMap<>();
//token should hold a valid active token
String token = null;
//put all the headers you need in that map
headers.put("Authorization", "Bearer " + token);
ResponseBody response = service.bulkUpdatePriceQuantity(headers, request).execute().body();
}
}
You need to have converter-gson, gson and retrofit in your classpath
Here is a fragment from my pom.xml
<dependency>
<groupId>com.squareup.retrofit2</groupId>
<artifactId>converter-gson</artifactId>
<version>2.3.0</version>
</dependency>
<dependency>
<groupId>com.google.code.gson</groupId>
<artifactId>gson</artifactId>
<version>2.8.2</version>
</dependency>
<dependency>
<groupId>com.squareup.retrofit2</groupId>
<artifactId>retrofit</artifactId>
<version>2.3.0</version>
</dependency>
Hope it helps
I'm using CXF ClientBuilder to send POST data to a REST service. The response I get back looks like this right now:
errorCode=206&errorMessage=blah+blah
I want to unmarshal this into fields in a POJO.
The following code block illustrates what I have right now:
public void validateToken(String token) {
WebTarget target = client.target(getHostPort()).path(getPath());
Builder request = target.request(MediaType.APPLICATION_JSON_TYPE);
Form form = new Form();
form.param("TokenID", token);
Response postResponse = request.post(Entity.entity(form, MediaType.APPLICATION_FORM_URLENCODED_TYPE));
System.out.println("postResponse[" + postResponse + "]");
System.out.println("response.text[" + postResponse.readEntity(String.class) + "]");
// CodeAndMessage codeAndMessage = request.post(Entity.entity(form, MediaType.APPLICATION_FORM_URLENCODED_TYPE), CodeAndMessage.class);
// System.out.println("codeAndMessage[" + codeAndMessage + "]");
}
public static class CodeAndMessage {
private String errorCode;
private String errorMessage;
public String getErrorCode() { return errorCode; }
public String getErrorMessage() { return errorMessage; }
public void setErrorCode(String errorCode) { this.errorCode = errorCode; }
public void setErrorMessage(String errorMessage) { this.errorMessage = errorMessage; }
#Override
public String toString() {
return new ToStringBuilder(this).
append("errorCode", getErrorCode()).
append("errorMessage", getErrorMessage()).
build();
}
}
As written right now, I get the response as I originally described. I'm trying to figure out some variation of those last commented-out lines to replace the first "request.post()" and the two following lines, to get the result I'm looking for.
Update:
I did find at least one way to do this, but I don't know if it's the best way.
Form responseForm = request.post(Entity.entity(form, MediaType.APPLICATION_FORM_URLENCODED_TYPE), Form.class);
System.out.println("responseForm[" + responseForm + "] map[" + responseForm.asMap() + "]");
return new CodeAndMessage().
errorCode(responseForm.asMap().getFirst("errorCode")).
errorMessage(responseForm.asMap().getFirst("errorMessage"));
The key was using the Form object for the response type. With this solution, I still have to reference the field names. Is there a cleaner way to do this?
Update:
I would guess that a cleaner solution would require implementing a MessageBodyReader for this CodeAndMessage class, but I'm not sure yet how to do that.
My MessageBodyReader implementation looks like this:
import java.io.IOException;
import java.io.InputStream;
import java.lang.annotation.Annotation;
import java.lang.reflect.Type;
import javax.ws.rs.Consumes;
import javax.ws.rs.WebApplicationException;
import javax.ws.rs.core.Form;
import javax.ws.rs.core.MediaType;
import javax.ws.rs.core.MultivaluedMap;
import javax.ws.rs.ext.MessageBodyReader;
import javax.ws.rs.ext.Provider;
import org.apache.cxf.jaxrs.provider.FormEncodingProvider;
#Provider
#Consumes(MediaType.APPLICATION_FORM_URLENCODED)
public class StuffResponseReader implements MessageBodyReader<StuffResponse> {
private FormEncodingProvider<Form> formProvider = new FormEncodingProvider<>();
private static final String PROP_ERROR_CODE = "errorCode";
private static final String PROP_ERROR_DESCRIPTION = "errorMessage";
...
#Override
public boolean isReadable(Class<?> type, Type genericType, Annotation[] annotations, MediaType mediaType) {
return type.isAssignableFrom(StuffResponse.class);
}
#Override
public StuffResponse readFrom(Class<StuffResponse> type, Type genericType, Annotation[] annotations,
MediaType mediaType, MultivaluedMap<String, String> httpHeaders, InputStream entityStream)
throws IOException, WebApplicationException {
Form form = formProvider.readFrom(Form.class, Form.class, annotations, mediaType, httpHeaders, entityStream);
MultivaluedMap<String, String> data = form.asMap();
return new StuffResponse().
errorCode(data.getFirst(PROP_ERROR_CODE)).
errorDescription(data.getFirst(PROP_ERROR_DESCRIPTION)).
...;
}
}
When creating the ClientBuilder, I register the MBR like this:
ClientBuilder builder = ClientBuilder.newBuilder().register(StuffResponseReader.class);
I'm creating a Jersey client for a GET service that has a List as query parameter. According to the documentation, it's possible to have a List as a query parameter (this information is also at #QueryParam javadoc), check it out:
In general the Java type of the method parameter may:
Be a primitive type;
Have a constructor that accepts a single String argument;
Have a static method named valueOf or fromString that accepts a single String argument (see, for example, Integer.valueOf(String) and java.util.UUID.fromString(String)); or
Be List, Set or SortedSet, where T satisfies 2 or 3 above. The resulting collection is read-only.
Sometimes parameters may contain more than one value for the same name. If this is the case then types in 4) may be used to obtain all values.
However, I can't figure out how to add a List query parameter using Jersey client.
I understand alternative solutions are:
Use POST instead of GET;
Transform the List into a JSON string and pass it to the service.
The first one is not good, because the proper HTTP verb for the service is GET. It is a data retrieval operation.
The second will be my option if you can't help me out. :)
I'm also developing the service, so I may change it as needed.
Thanks!
Update
Client code (using json)
Client client = Client.create();
WebResource webResource = client.resource(uri.toString());
SearchWrapper sw = new SearchWrapper(termo, pagina, ordenacao, hits, SEARCH_VIEW, navegadores);
MultivaluedMap<String, String> params = new MultivaluedMapImpl();
params.add("user", user.toUpperCase());
params.add("searchWrapperAsJSON", (new Gson()).toJson(sw));
ClientResponse clientResponse = webResource .path("/listar")
.queryParams(params)
.header(HttpHeaders.AUTHORIZATION, AuthenticationHelper.getBasicAuthHeader())
.get(ClientResponse.class);
SearchResultWrapper busca = clientResponse.getEntity(new GenericType<SearchResultWrapper>() {});
#GET does support List of Strings
Setup:
Java : 1.7
Jersey version : 1.9
Resource
#Path("/v1/test")
Subresource:
// receive List of Strings
#GET
#Path("/receiveListOfStrings")
public Response receiveListOfStrings(#QueryParam("list") final List<String> list){
log.info("receieved list of size="+list.size());
return Response.ok().build();
}
Jersey testcase
#Test
public void testReceiveListOfStrings() throws Exception {
WebResource webResource = resource();
ClientResponse responseMsg = webResource.path("/v1/test/receiveListOfStrings")
.queryParam("list", "one")
.queryParam("list", "two")
.queryParam("list", "three")
.get(ClientResponse.class);
Assert.assertEquals(200, responseMsg.getStatus());
}
If you are sending anything other than simple strings I would recommend using a POST with an appropriate request body, or passing the entire list as an appropriately encoded JSON string. However, with simple strings you just need to append each value to the request URL appropriately and Jersey will deserialize it for you. So given the following example endpoint:
#Path("/service/echo") public class MyServiceImpl {
public MyServiceImpl() {
super();
}
#GET
#Path("/withlist")
#Produces(MediaType.TEXT_PLAIN)
public Response echoInputList(#QueryParam("list") final List<String> inputList) {
return Response.ok(inputList).build();
}
}
Your client would send a request corresponding to:
GET http://example.com/services/echo?list=Hello&list=Stay&list=Goodbye
Which would result in inputList being deserialized to contain the values 'Hello', 'Stay' and 'Goodbye'
i agree with you about alternative solutions which you mentioned above
1. Use POST instead of GET;
2. Transform the List into a JSON string and pass it to the service.
and its true that you can't add List to MultiValuedMap because of its impl class MultivaluedMapImpl have capability to accept String Key and String Value. which is shown in following figure
still you want to do that things than try following code.
Controller Class
package net.yogesh.test;
import java.util.List;
import javax.ws.rs.GET;
import javax.ws.rs.Path;
import javax.ws.rs.Produces;
import javax.ws.rs.QueryParam;
import com.google.gson.Gson;
#Path("test")
public class TestController {
#Path("testMethod")
#GET
#Produces("application/text")
public String save(
#QueryParam("list") List<String> list) {
return new Gson().toJson(list) ;
}
}
Client Class
package net.yogesh.test;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import javax.ws.rs.core.MultivaluedMap;
import com.sun.jersey.api.client.ClientResponse;
import com.sun.jersey.api.client.WebResource;
import com.sun.jersey.api.client.config.ClientConfig;
import com.sun.jersey.api.client.config.DefaultClientConfig;
import com.sun.jersey.core.util.MultivaluedMapImpl;
public class Client {
public static void main(String[] args) {
String op = doGet("http://localhost:8080/JerseyTest/rest/test/testMethod");
System.out.println(op);
}
private static String doGet(String url){
List<String> list = new ArrayList<String>();
list = Arrays.asList(new String[]{"string1,string2,string3"});
MultivaluedMap<String, String> params = new MultivaluedMapImpl();
String lst = (list.toString()).substring(1, list.toString().length()-1);
params.add("list", lst);
ClientConfig config = new DefaultClientConfig();
com.sun.jersey.api.client.Client client = com.sun.jersey.api.client.Client.create(config);
WebResource resource = client.resource(url);
ClientResponse response = resource.queryParams(params).type("application/x-www-form-urlencoded").get(ClientResponse.class);
String en = response.getEntity(String.class);
return en;
}
}
hope this'll help you.
One could use the queryParam method, passing it parameter name and an array of values:
public WebTarget queryParam(String name, Object... values);
Example (jersey-client 2.23.2):
WebTarget target = ClientBuilder.newClient().target(URI.create("http://localhost"));
target.path("path")
.queryParam("param_name", Arrays.asList("paramVal1", "paramVal2").toArray())
.request().get();
This will issue request to following URL:
http://localhost/path?param_name=paramVal1¶m_name=paramVal2
GET Request with JSON Query Param
package com.rest.jersey.jerseyclient;
import com.sun.jersey.api.client.Client;
import com.sun.jersey.api.client.ClientResponse;
import com.sun.jersey.api.client.WebResource;
public class JerseyClientGET {
public static void main(String[] args) {
try {
String BASE_URI="http://vaquarkhan.net:8080/khanWeb";
Client client = Client.create();
WebResource webResource = client.resource(BASE_URI);
ClientResponse response = webResource.accept("application/json").get(ClientResponse.class);
/*if (response.getStatus() != 200) {
throw new RuntimeException("Failed : HTTP error code : "
+ response.getStatus());
}
*/
String output = webResource.path("/msg/sms").queryParam("search","{\"name\":\"vaquar\",\"surname\":\"khan\",\"ext\":\"2020\",\"age\":\"34\""}").get(String.class);
//String output = response.getEntity(String.class);
System.out.println("Output from Server .... \n");
System.out.println(output);
} catch (Exception e) {
e.printStackTrace();
}
}
}
Post Request :
package com.rest.jersey.jerseyclient;
import com.rest.jersey.dto.KhanDTOInput;
import com.sun.jersey.api.client.Client;
import com.sun.jersey.api.client.ClientResponse;
import com.sun.jersey.api.client.WebResource;
import com.sun.jersey.api.client.config.ClientConfig;
import com.sun.jersey.api.client.config.DefaultClientConfig;
import com.sun.jersey.api.json.JSONConfiguration;
public class JerseyClientPOST {
public static void main(String[] args) {
try {
KhanDTOInput khanDTOInput = new KhanDTOInput("vaquar", "khan", "20", "E", null, "2222", "8308511500");
ClientConfig clientConfig = new DefaultClientConfig();
clientConfig.getFeatures().put( JSONConfiguration.FEATURE_POJO_MAPPING, Boolean.TRUE);
Client client = Client.create(clientConfig);
// final HTTPBasicAuthFilter authFilter = new HTTPBasicAuthFilter(username, password);
// client.addFilter(authFilter);
// client.addFilter(new LoggingFilter());
//
WebResource webResource = client
.resource("http://vaquarkhan.net:12221/khanWeb/messages/sms/api/v1/userapi");
ClientResponse response = webResource.accept("application/json")
.type("application/json").put(ClientResponse.class, khanDTOInput);
if (response.getStatus() != 200) {
throw new RuntimeException("Failed : HTTP error code :" + response.getStatus());
}
String output = response.getEntity(String.class);
System.out.println("Server response .... \n");
System.out.println(output);
} catch (Exception e) {
e.printStackTrace();
}
}
}
I want to use the Google Shortener API. I want to use the google api java client library to post a request and parse the JSON response.
Next, I post the code I have tried:
import java.io.IOException;
import net.sf.json.JSONObject;
import com.google.api.client.googleapis.GoogleHeaders;
import com.google.api.client.googleapis.GoogleTransport;
import com.google.api.client.googleapis.json.JsonCParser;
import com.google.api.client.http.HttpRequest;
import com.google.api.client.http.HttpResponse;
import com.google.api.client.http.HttpTransport;
import com.google.api.client.json.JsonHttpContent;
import com.google.api.client.util.GenericData;
public class GoogleShortener {
public static final String GOOGL_URL = "https://www.googleapis.com/urlshortener/v1/url";
public static void main(String[] args) {
// setup up the HTTP transport
HttpTransport transport = GoogleTransport.create();
// add default headers
GoogleHeaders defaultHeaders = new GoogleHeaders();
transport.defaultHeaders = defaultHeaders;
transport.defaultHeaders.put("Content-Type", "application/json");
transport.addParser(new JsonCParser());
// build the HTTP GET request and URL
GenericData data = new GenericData();
data.put("longUrl", "http://www.google.com/");
JsonHttpContent content = new JsonHttpContent();
content.data = data;
HttpRequest request = transport.buildPostRequest();
request.content = content;
request.setUrl(GOOGL_URL);
HttpResponse response;
try {
JSONObject json = request.execute().parseAs(JSONObject.class);
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
When I execute the above code, I get the next output:
Exception in thread "main" java.lang.IllegalArgumentException: data key not found
at com.google.api.client.googleapis.json.JsonCParser.parserForResponse(JsonCParser.java:77)
at com.google.api.client.googleapis.json.JsonCParser.parse(JsonCParser.java:47)
at com.google.api.client.http.HttpResponse.parseAs(HttpResponse.java:261)
at GoogleShortener.main(GoogleShortener.java:43)
Any idea how to set the JsonCParser properly?
ERROR PATH
In the beginning I was not setting properly the request content. As pointed by #dwb, the request content should be set:
GenericData data = new GenericData();
data.put("longUrl", "http://www.google.com/");
JsonHttpContent content = new JsonHttpContent();
content.data = data;
request.content = content;
If you do not set the content properly, you will get the next error
com.google.api.client.http.HttpResponseException:
411 Length Required at
com.google.api.client.http.HttpRequest.execute(HttpRequest.java:209)
at
GoogleShortener.main(GoogleShortener.java:32)
You need to add JSON content to the request body like this:
GenericData data = new GenericData();
data.put("longUrl", "http://www.google.com/");
JsonHttpContent content = new JsonHttpContent();
content.data = data;
request.content = content;
For the response, try using the JsonHttpParser instead of JsonCParser. You'll need to create a subclass of GenericJson that contains fields with a #Key annotation for every JSON property you want to retrieve. You can use response.parseAsString() to see all of the properties available.
Here's a full working example:
import com.google.api.client.googleapis.GoogleHeaders;
import com.google.api.client.googleapis.GoogleTransport;
import com.google.api.client.http.HttpRequest;
import com.google.api.client.http.HttpResponse;
import com.google.api.client.http.HttpTransport;
import com.google.api.client.json.GenericJson;
import com.google.api.client.json.JsonHttpContent;
import com.google.api.client.json.JsonHttpParser;
import com.google.api.client.util.GenericData;
import com.google.api.client.util.Key;
public class Shortener {
public static final String GOOGL_URL = "https://www.googleapis.com/urlshortener/v1/url";
/**
* #param args
*/
public static void main(String[] args) throws Exception {
// setup up the HTTP transport
HttpTransport transport = GoogleTransport.create();
// add default headers
GoogleHeaders defaultHeaders = new GoogleHeaders();
transport.defaultHeaders = defaultHeaders;
transport.defaultHeaders.put("Content-Type", "application/json");
transport.addParser(new JsonHttpParser());
// build the HTTP GET request and URL
HttpRequest request = transport.buildPostRequest();
request.setUrl(GOOGL_URL);
GenericData data = new GenericData();
data.put("longUrl", "http://www.google.com/");
JsonHttpContent content = new JsonHttpContent();
content.data = data;
request.content = content;
HttpResponse response = request.execute();
Result result = response.parseAs(Result.class);
System.out.println(result.shortUrl);
}
public static class Result extends GenericJson {
#Key("id")
public String shortUrl;
}
}
The code given by dwb is correct but it is using deprecated methods of the google client api.
Implementation with current library support is as follows :
import java.util.HashMap;
import java.util.Map;
import com.google.api.client.googleapis.javanet.GoogleNetHttpTransport;
import com.google.api.client.http.GenericUrl;
import com.google.api.client.http.HttpContent;
import com.google.api.client.http.HttpHeaders;
import com.google.api.client.http.HttpRequest;
import com.google.api.client.http.HttpResponse;
import com.google.api.client.http.HttpTransport;
import com.google.api.client.http.json.JsonHttpContent;
import com.google.api.client.json.GenericJson;
import com.google.api.client.json.JsonObjectParser;
import com.google.api.client.json.jackson.JacksonFactory;
import com.google.api.client.util.Key;
public class ShortenUrl {
/**
* #param args
*/
public static void main(String[] args) throws Exception {
HttpTransport httpTransport = GoogleNetHttpTransport.newTrustedTransport();
HttpHeaders headers = new HttpHeaders();
JsonObjectParser parser = new JsonObjectParser(new JacksonFactory());
GenericUrl url = new GenericUrl("https://www.googleapis.com/urlshortener/v1/url");
Map<String, String> json = new HashMap<String, String>();
json.put("longUrl", "http://www.google.com/");
final HttpContent content = new JsonHttpContent(new JacksonFactory(), json);
HttpRequest request = httpTransport.createRequestFactory().buildPostRequest(url, content);
try {
HttpResponse response = request.execute();
Result result = response.parseAs(Result.class);
System.out.println(result.shortUrl);
} catch (Exception e) {
e.printStackTrace();
}
}
public static class Result extends GenericJson {
#Key("id")
public String shortUrl;
}
}
Note : You should use your Oauth 2.0 credentials to use google api services.