How to make a GET Request using okhttp - android-networking

I am new to Android Development and I would like to know how to perform a GET request using okhttp. I have referred http://square.github.io/okhttp/, but they only have examples of POST request. I have tried this -
okHttpClientLogin = new OkHttpClient();
requestBodyLogin = new FormBody.Builder()
.addEncoded("name", name_input) // params
.addEncoded("keys", keys_input) //params
.build();
requestLogin = new Request.Builder()
.addHeader("Authorization", token_type + " " +access_token)
.url(LOGIN_URL)
.get()
.build();
and got an Error :
{"status":{"status":206,"msg":"No record found"},"user":null}
I know why this error is coming, because the params have not been entered. I also tried passing requestBodyLogin inside .get() but it's not allowing.

Since OkHTTP 2.4, there's the function addQueryParameter. You can either use a HttpUrl, a String or a java.net.URL as url.
Basically, just create a new HttpUrl.Builder() and use the function addQueryParameter.
Example taken from the javadocs:
HttpUrl url = new HttpUrl.Builder()
.scheme("https")
.host("www.google.com")
.addPathSegment("search")
.addQueryParameter("q", "polar bears")
.build();
http://square.github.io/okhttp/3.x/okhttp/okhttp3/HttpUrl.html
http://square.github.io/okhttp/2.x/okhttp/com/squareup/okhttp/HttpUrl.Builder.html#addQueryParameter-java.lang.String-java.lang.String-

Related

How to set url encoded form entity and add params to form entity in rest assured?

The below sample code is in http client , But I want to write the same in Rest Assured. I know we can use the http lib in rest assured as well, But I want to have in Rest assured
HttpPost pst = new HttpPost(baseUrl, "j_spring_security_check"))
pst.setHeader("Content-Type", "application/x-www-form-urlencoded")
ArrayList<NameValuePair> postParam = new ArrayList<NameValuePair>()
postParam .add(new BasicNameValuePair("j_username",username))
postParam .add(new BasicNameValuePair("j_password",password))
UrlEncodedFormEntity formEntity23 = new UrlEncodedFormEntity(postParam)
pst.setEntity(formEntity23 )
HttpResponse response = httpclient.execute(pst);
For Rest Assured you can use below code snippet.
Response response = RestAssured
.given()
.header("Content-Type", "application/x-www-form-urlencoded")
.formParam("j_username", "uName")
.formParam("j_password", "pwd")
.request()
.post(url);
As, your application is using form url-encoded content type you can set the Header type to this as mentioned above.
Hope, this helps you.
#Test
public void postRequestWithPayload_asFormData() {
given().contentType(ContentType.URLENC.withCharset("UTF-8")).formParam("foo1", "bar1").formParam("foo2", "bar2").log().all()
.post("https://postman-echo.com/post").then().log().all().statusCode(200)
.body("form.foo1", equalTo("bar1"));
}
Add content type of URLENC with charaset as UTF-8. It works will latest rest assured.

Can any body share me java code to make a one Rest api call to IBM BPM Cloud

Can any body share a java client code which makes a Rest calls to IBM Cloud BPM. Basically I want to know how to authenticate IBM Cloud BPM.
I tried the following code but it is not working
String user_info_url="https://ustrial01.bpm.ibmcloud.com/bpm/dev/rest/bpm/wle/v1/user/current?includeInternalMemberships=true&parts=all";
logger.info("user_info_url :" + user_info_url);
HttpClient client = HttpClientBuilder.create().build();
HttpGet get = new HttpGet(user_info_url);
String authData = "rajesh.kohir123#gmail.com" + ":" + "password";
String encoded = new sun.misc.BASE64Encoder().encode(authData .getBytes());
get.setHeader("Content-Type", "application/json");
get.setHeader("Accept", "application/json");
get.setHeader("Authorization", "Basic " + encoded);
HttpResponse cgResponse = client.execute(get);
if(cgResponse.getStatusLine().getStatusCode() != 200) {
logger.info("IBM Rest call failed");
}
if(cgResponse.getStatusLine().getStatusCode() == 200) {
logger.info("IBM Rest call Succeded");
String content = EntityUtils.toString(cgResponse.getEntity());
logger.info(content);
}
Any help is greatly appreciated
I ran your code and just made the changes in URL. It worked. I hope this helps you.
Following is the URL I used to execute an exposed service :
https://vhost031.bpm.ibmcloud.com/bpm/dev/rest/bpm/wle/v1/service/OMS#Greetings
I used the following code to add the parameters :
String parameters = "{'name':'pramod'}";
URIBuilder builder = new URIBuilder("https://vhost031.bpm.ibmcloud.com/bpm/dev/rest/bpm/wle/v1/service/OMS#Greetings");
List nameValuePairs = new ArrayList();
nameValuePairs.add(new BasicNameValuePair("action", "start"));
nameValuePairs.add(new BasicNameValuePair("params", parameters));
nameValuePairs.add(new BasicNameValuePair("createTask", "false"));
nameValuePairs.add(new BasicNameValuePair("parts", "all"));
builder.setParameters(nameValuePairs);
HttpGet get = new HttpGet(builder.build());
Download the download.zip form the post.
Look at the SampleBPDProcessTests.java - Line no 103
JSONObject results = bpmClient.runBPD(BPD_ID, PROCESS_APP_ID, bpdArgs);
The actual Java Code for Rest call is available as part of "bpm-rest-client.jar"
Try this concept.
Sample Java code to start a process:
OkHttpClient client = new OkHttpClient();
Request request = new Request.Builder()
.url("https://ustrial03.bpm.ibmcloud.com:443/bpm/dev/rest/bpm/wle/v1/process?
processAppId=3u092jr02j-djaodaj.u092302c166c1&bpdId=25.jklaklaa-539a-4150-
b63e-9ef94e96e521&action=start")
.put(null)
.addHeader("Content-Type", "application/x-www-form-urlencoded")
.addHeader("Accept", "application/json")
.addHeader("Connection", "keep-alive")
.addHeader("Authorization", "Basic YXJrYX24223232hQGRlbG9pdHRlLmNvbTpkZWZjb240QA==")
.addHeader("Cache-Control", "no-cache")
.addHeader("Postman-Token", "f46c1525-7a75-954c-9265-bb2b21a57f16")
.build();
Response response = client.newCall(request).execute();
A full explanation of REST integration with BPM Cloud can be found in my answer at:
How to run IBM BPM Rest api call from Post man client

Play WS API Making nested requests - WSClient

I want to make two HTTP requests(POST) using play2 WSRequest where some information from the first response is send to the second request. I tried to do this in following manner to make sure second request is only triggers after the first one is completed. But I get Type mismatch: cannot convert from F.Promise to F.Promise error
public Promise<Result> executeAPI(String apiName,JsonNode requestBody){
WSRequest pcLoginRequest = ws.url("http://xxxxx.qa.local:8080/mytest/rest/login");
pcLoginRequest.setContentType("application/json");
pcLoginRequest.setHeader("X-x-Password", "xxxxx")
.setHeader("X-x-Username", "xxxxx")
.setHeader("X-x-Content-Type", "application/json");
Promise<Result> myPromise = pcLoginRequest.post("").map(response -> {
ProApiSession.getInstanceOf().setProToeken(response.asJson().get("token").asText());
WSRequest pcrequest = ws.url("http://xxxxx.qa.local:8080/mytest/rest/api/" + apiName);
pcrequest.setContentType("application/json");
pcrequest.setHeader("X-x-Token",ProApiSession.getInstanceOf().getProToeken() )
.setBody(requestBody)
.setHeader("X-x-Content-Type", "application/json");
Promise<Result> myPromise2 = pcLoginRequest.post(requestBody).map(response2 -> {
return Results.ok(response2.asJson());
});
return myPromise;
});
Can someone please suggest how to do nested request using WSRequest in play. (import play.libs.ws.* )
Java 8 type inference errors are bad at the best of times. Since the result of the lambda you're passing to the first map is Promise<Result>, what you're trying to assign to myPromise is Promise<Promise<Result>>. What you actually want to do is replace the map call with flatMap, which is so named because is "flattens" the nested promise to just be a single promise.

Cannot access google trends using HttpClient

I'm kind of newbie to this...Basicly I need to run a script to download .csv files from google trends. I wrote the following code according to this reference , the code is like:
HttpClient client = new DefaultHttpClient();
HttpPost post = new HttpPost("https://www.google.com/accounts/ClientLogin");
try {
List<NameValuePair> nameValuePairs = new ArrayList<NameValuePair>;
nameValuePairs.add(new BasicNameValuePair("Email", "myEmail"));
nameValuePairs
.add(new BasicNameValuePair("Passwd", "myPasswd"));
nameValuePairs.add(new BasicNameValuePair("accountType", "GOOGLE"));
nameValuePairs.add(new BasicNameValuePair("source",
"Google-cURL-Example"));
nameValuePairs.add(new BasicNameValuePair("service", "xapi"));
post.setEntity(new UrlEncodedFormEntity(nameValuePairs));
HttpResponse response = client.execute(post);
BufferedReader rd = new BufferedReader(new InputStreamReader(response.getEntity().getContent()));
String line = "";
while ((line = rd.readLine()) != null) {
System.out.println(line);
if (line.startsWith("SID=")) {
String key = line.substring(4);
// Do something with the key
} catch (Exception e) {
}
I got the information about SID, LSID, Auth, but don't know how to use these information. I guess I should add these cookies in my following request, but don't know exactly how. I wrote another piece of code to connect to the certain URL, but I keep getting this message "You must be signed in to export data from Google Trends." The code is here if it helps:
URL url = new URL(myUrl);
HttpURLConnection conn = (HttpURLConnection) url.openConnection();
conn.setDoInput(true);
conn.setDoOutput(true);
conn.setInstanceFollowRedirects(true);
conn.addRequestProperty("Content-Type", "application/x-www-form-urlencoded");
conn.addRequestProperty("Authorization", "SID"+key);
conn.addRequestProperty("Email", "myEmail");
conn.addRequestProperty("Passwd", "myPasswd");
conn.setReadTimeout(5000);
conn.connect();
I searched around and found few useful information, anyone could help?
Does it have to be in Java? In python, it's as simple as this:
from pyGTrends import pyGTrends
connector = pyGTrends('google username','google password')
connector.download_report(('keyword1', 'keyword2'))
print connector.csv()
You'll need the google trends api library.
If it has to be Java, you may want to look at the HttpClient examples from Apache. "Form based logon" and "client authentication" may both be relevant.
I have just coded this:
https://github.com/elibus/j-google-trends-api
It is an unofficial Java implementation of Google Trends API. You could use it to easily access Google Trends or you might want to have a look at the code to see it works.
Anyway the authentication flow works as follows (all the steps are required):
Fetch https://accounts.google.com/ServiceLoginAuth and parse the GALX id
Post username/password + GALX
Get http://www.google.com
Then you can access Google Trend with relaxed QoS policies for authenticated users.

Invoking REST API for making new component in JIRA

I've to make a new Component in JIRA
I found out the POST url /rest/api/2/component for making new component, but i'm unable to know what type of inputs to be given.
DefaultHttpClient httpClient = new DefaultHttpClient();
HttpPost postRequest = new HttpPost("http://localhost:8080/rest/api/2/component/");
String authorization = JiraRequestResponseUtil.conversionForAuthorization();
postRequest.setHeader("Authorization", authorization);
StringEntity input = new StringEntity("\"name\":\"Component 1\",\"description\":\"This is a TEST JIRA component\" ,\"leadUserName\":\"fred\",\"assigneeType\":\"PROJECT_LEAD\",\"isAssigneeTypeValid\":\"false\",\"project\":\"TEST\"");
input.setContentType("application/json");
postRequest.setEntity(input);
HttpResponse response = httpClient.execute(postRequest);
this is the code i'm implementing.
Output i'm getting is Failed : HTTP error code : 400
Plz help.
we can't tell you. You need to find documentation on the service you are posting to.
The above code is correct, just add the { & } to the JSON string.