Google API Java GET request with body content - java

My Goal is to request GoogleTaskAPI for TASKLIST with specified no.of result.
It works fine, If I m passing no requestBody. But I need to pass request parameter to specific number of results to be returned. When I do that, it creates new Tasklist, Instead of listing. So how to do this?
My Code:
GoogleAccessProtectedResource access = new GoogleAccessProtectedResource(accessToken, httpTransport, jsonFactory, clientId, clientSecret, refreshToken);
HttpRequestFactory rf = httpTransport.createRequestFactory(access);
String endPointUrl = "https://www.googleapis.com/tasks/v1/users/#me/lists";
String requestBody = "{\"maxResults\":3}";
GenericUrl endPoint = new GenericUrl(endPointUrl);
ByteArrayContent content = new ByteArrayContent("application/json", requestBody.getBytes());
//Try 0: Works, But Retrieving all of my Tasklist, I need only 3
//HttpRequest request = rf.buildGetRequest(endPoint);
//-------
//Try 1: Fails to retrieve
//HttpRequest request = rf.buildGetRequest(endPoint);
//request.setContent(content);
//request.getContent().writeTo(System.out);
//-------
//Try 2: Fails to retrieve
HttpRequest request = rf.buildRequest(HttpMethod.GET, endPoint, content);
request.getContent().writeTo(System.out);
//-------
HttpResponse response = request.execute();
String str = response.parseAsString();
utils.log(str);

maxResults is a query parameter, not a request parameter, so you can just put it in the url:
String endPointUrl = "https://www.googleapis.com/tasks/v1/users/#me/lists?maxResults=3";
You should also consider using the Java client's Tasks interface for making requests; it may be a little easier since it handles the details of the url for you:
http://code.google.com/p/google-api-java-client/wiki/APIs#Tasks_API

Related

How to add parameter in request URL( Java 11)?

I'm absolute beginner in java. Trying to send some http request using the built in java httpclient.
How can I add the request parameters into the URI in such format:
parameter = hi
url = "https://www.url.com?parameter=hi"
With the code, I'm using, I can only set the headers but not the request parameters
var client = HttpClient.newHttpClient();
var request = HttpRequest.newBuilder(URI.create(url))
.GET()
.build();
var reponse = client.send(request, HttpResponse.BodyHandlers.ofString());
return reponse.body();
Thank you very much!
With native Java 11, it has to be done like you did. You need to add the parameters within the url parameter already. Or you need to create your own builder that allows you to append parameter.
However, your requested behaviour is possible if you make use of libraries. One way to do it is to make use of Apache URIBuilder
var client = HttpClient.newHttpClient();
URI uri = new URIBuilder(httpGet.getURI())
.addParameter("parameter", "hi")
.build();
var request = HttpRequest.newBuilder(uri)
.GET()
.build();
var reponse = client.send(request, HttpResponse.BodyHandlers.ofString());
return reponse.body();
You don't have methods for adding parameters, but you can use String.format() to format the URL nicely.
final static String URL_FORMAT = "http://url.com?%s=%s";
final String request = String.format(URL_FORMAT, "paramater", "hi");

How to make HttpPut request with string array as body to it in JAVA?

I have a requirement to call a rest api put method which accepts one parameter Body(of type arrray[string]) which is to be passed to "BODY" not query parameter.
Below is the value that this parameter accepts:
[
"string"
]
These are the steps that I tried to make the call:
created an oauth consumer object that is used to sign the request and httpclient object to execute the request
consumer = new CommonsHttpOAuthConsumer("abc", "def");
requestConfig = RequestConfig.custom().setConnectTimeout(300 * 1000).build();
httpClient = HttpClientBuilder.create().setDefaultRequestConfig(requestConfig).build();
Creating the put request with json
URL url = new URL("http://www.example.com/resource");
String[] dfNames = {};
dfNames[0] = "test";
putreq = new HttpPut(url);
putreq.setHeader("Id","xyz");
StringEntity input = new StringEntity(dfNames); //Getting compilation error
input.setContentType("application/json");
putreq.setEntity(input);
Executing the request to get the response code
updateresponse = httpClient.execute(putreq);
int updatehttpResponseCode = updateresponse.getStatusLine().getStatusCode();
System.out.println("post Response Code :: " + updatehttpResponseCode);
if (updatehttpResponseCode == 200)
{
System.out.println("PuT request worked);
}
else
{
System.out.println("PuT request not worked");
}
OUTPUT:
I am getting a compilation error when running this since the string entity class cannot accept string array. Is there any other class which will accept the string[] array?
As discussed in the comments, the HTTP PUT body is just a string, so just convert the array to String (with Arrays.toString() or any other way) and use it.

use docusign api creates envelopes, error: Object moved

I consulted the API documentation and sent it successfully in api explorer-> Envelopes: create. I also got json & request path & token. I used httpclient post in java and received Object moved Object moved to here . Does anyone know what I missed?
`
DocsignDocument docsignDocument = new DocsignDocument();
docsignDocument.setDocumentBase64
docsignDocument.setDocumentId("1");
docsignDocument.setFileExtension("pdf");
docsignDocument.setName("Test.pdf");
list.add(docsignDocument);
Recipients recipients = new Recipients();
Signers signers = new Signers();
signers.setEmail("xxxx");
signers.setName("Qin");
signers.setRecipientId("1");
Signers signers1 = new Signers();
signers1.setEmail("xxx#qq.com");
signers1.setName("OYX");
signers1.setRecipientId("2");
List<Signers> signersList = new ArrayList<>();
signersList.add(signers);
signersList.add(signers1);
recipients.setSigners(signersList);
dataJson.put("documents",list);
dataJson.put("emailSubject","TEST");
dataJson.put("recipients",recipients);
dataJson.put("status","sent");
String data = dataJson.toJSONString();
String results2 = HttpDocusignUtils.httpPostJson("https://account-d.docusign.com/restapi/v2.1/accounts/xxx/envelopes",access_token,data)`
post request:
public static String httpPostJson(String uri, String token, String obj) {
String result = "";
try {
CloseableHttpClient httpclient = HttpClients.createDefault();
HttpPost httpPost = new HttpPost(uri);
httpPost.addHeader("Content-Type", "application/json"); // 添加请求头
httpPost.addHeader("Authorization","Bearer "+token);
httpPost.addHeader("Accept-Encoding","gzip,deflate,sdch");
httpPost.setEntity(new StringEntity(obj));
System.out.println(httpPost);
HttpResponse response = httpclient.execute(httpPost);
HttpEntity entity = response.getEntity();
if (entity != null) {
InputStream instreams = entity.getContent();
result = convertStreamToString(instreams);
System.out.println(result);
}
} catch (Exception e) {
e.getMessage();
}
return result;
}
https://account-d.docusign.com/restapi/v2.1/accounts/xxx/envelopes is not a valid DocuSign endpoint.
The Account Server (account-d.docusign.com) is used to get a token and make a UserInfo call to determine the correct base URL for a particular account.
Because you're in the Demo environment, your base url will begin with https://demo.docusign.net
Well, one issue is that the the Document model in Java is Document from
import com.docusign.esign.model.Document;
To debug, I suggest using the DocuSign API logging feature. Then update (edit) your question to include the JSON shown in the log.
Were you able to run the code examples for Java? See eg-03-java-auth-code-grant
Also, please tell us (by editing your question) what you are trying to do.
Creates envelopes - Use Base Url in Api Call
https://demo.docusign.net/restapi/v2.1/accounts/
Error Reason is use Wrong url - https://account-d.docusign.com/restapi/v2.1/accounts/
DocuSign Developers Documentation

Spring Boot TestRestTemplate: Pass along session id

I've got a Spring Boot application with some tests. The application's 'happy-path' requires that the user send a request to start a session, then it can make other requests to other services.
I'm trying to test these other services, but I need a session started first. My mindset was as follows:
Hit the session start endpoint
Get the session cookie from that request
Slap that cookie onto future requests made during testing.
To achieve that, I've got this mess:
String s = t.postForEntity(loginUrl, remoteSessionPacket, String.class)
.getHeaders()
.get("Set-Cookie").get(0);
String[] split = s.split(";");
String sessionId = "";
for (String s1 : split) {
if(s1.contains("SESSION"))
{
sessionId = s1;
}
}
HttpHeaders headers = new HttpHeaders();
headers.add("SESSION", sessionId);
HttpEntity<?> httpEntity = new HttpEntity<>(headers);
RemoteDTOPacket= new RemoteDTOPacket();
packet.Token = UUID.randomUUID().toString();
String url = "http://localhost:" + port + "/domain/SomeFunction";
ResponseEntity<ResponsePacket> response = t.postForEntity(url, packet, ResponsePacket.class, httpEntity);
Assert.assertEquals(0, (long) response.getBody().count);
Obviously, this doesn't work and errors are thrown with abandon.
Does anyone know how to accomplish what I'm trying to do?
Any help is greatly appreciated.
Session id is stored in cookie that is stored in "Cookie" header - not in separate request header. Something like this should work:
List<String> coockies = t.postForEntity(loginUrl, remoteSessionPacket, String.class)
.getHeaders()
.get("Set-Cookie");
HttpHeaders requestHeaders = new HttpHeaders();
requestHeaders.put(HttpHeaders.COOKIE, coockies);
HttpEntity<Void> requestEntity = new HttpEntity<>(requestHeaders);
Or you can get exact session id cookie that will be most probably stored under "JSESSIONID" key.

Convert GetEntity().GetContent() from Java to C#

I need to convert the following code from Java to C# when I'm using restAPI in C#.
In java :
HttpGet statusGet = new HttpGet(fileUrl);
statusGet.setHeader("X-API-TOKEN", API_TOKEN);
HttpResponse response = httpClient.execute(statusGet);
// Extract exported file
ZipInputStream zs = new ZipInputStream(response.getEntity().getContent());
In C# this is what I have:
var client1 = new RestClient(fileUrl);
var request1 = new RestRequest(Method.GET);
request1.AddHeader("X-API-TOKEN", "API_TOKEN");
request1.AddHeader("content-type", "application/json");
request1.AddParameter("application/json", "{\n\t\"format\" : \"csv\",\n\t\"surveyId\" : \"_surveyId\"\n}", ParameterType.RequestBody);
IRestResponse responsedata = client1.Execute(request1);
var download=client1.DownloadData(request1);
MemoryStream stream = new MemoryStream(download);
ZipInputStream zs = new ZipInputStream(stream);
using (ZipFile zip1 = ZipFile.Read(zs))
I have no clue how to implement response.getEntity().getContent(). I believe it is getting the Stream(Containing a zip file?)
Updated: So I get the byte array from client1.DownloadData(request1), looks like it is not right to convert it to stream (has readtimeout exception). and it will not be able to read from zipfile.read
Thank you so much for your help
Are you getting any specific errors? It looks like you are implementing this using RestSharp. Have you followed their examples and read through their documentation?
I have not personally used this third-party solution, but immediately on their front page they have the following example that does exactly what you are trying to do:
var client = new RestClient("http://example.com");
// client.Authenticator = new HttpBasicAuthenticator(username, password);
var request = new RestRequest("resource/{id}", Method.POST);
request.AddParameter("name", "value"); // adds to POST or URL querystring based on Method
request.AddUrlSegment("id", "123"); // replaces matching token in request.Resource
// easily add HTTP Headers
request.AddHeader("header", "value");
// add files to upload (works with compatible verbs)
request.AddFile(path);
// execute the request
IRestResponse response = client.Execute(request);
var content = response.Content; // raw content as string
// or automatically deserialize result
// return content type is sniffed but can be explicitly set via RestClient.AddHandler();
RestResponse<Person> response2 = client.Execute<Person>(request);
var name = response2.Data.Name;
// easy async support
client.ExecuteAsync(request, response => {
Console.WriteLine(response.Content);
});
// async with deserialization
var asyncHandle = client.ExecuteAsync<Person>(request, response => {
Console.WriteLine(response.Data.Name);
});
// abort the request on demand
asyncHandle.Abort();
It looks like you would want to access the IRestResponse.Content property, or to deserialize using the RestClient.Execute<T>(RestRequest request) function.

Categories

Resources