Apidaze REST API HTTP POST Call in Android/Java - java

I am trying to send SMS messages when a button is clicked in an Android app. I have the SMS sending code in Python using a REST API. The template looks like so:
import requests
url = "https://api.apidaze.io/{{api_key}}/sms/send"
querystring = {"api_secret":"{{api_secret}}"}
payload = "from=15558675309&to=15551234567&body=Have%20a%20great%20day."
headers = {'Content-Type': 'application/x-www-form-urlencoded'}
response = requests.request("POST", url, data=payload, headers=headers,
params=querystring)
print(response.text)
Because I am making an Android app, I need this to be in Java, but I am having trouble making the same POST request with the same parameters, headers, and body in JAVA.
Does anyone know how to make convert this template into something I can use for an Android app in Java?

There is a port of Apache Http Client for Android:
http://hc.apache.org/httpcomponents-client-4.3.x/android-port.html
Check the documentation, a simple POST request is very easy using this library:
HttpPost httpPost = new HttpPost("https://api.apidaze.io/" + api_key + "/sms/send");
String json = "{"api_secret":" + api_secret + "}";
StringEntity entity = new StringEntity(json);
httpPost.setEntity(entity);
httpPost.setHeader("Content-type", "application/x-www-form-urlencoded");
CloseableHttpResponse response = client.execute(httpPost);

Related

How do we consume rest api with Http basic authentication in spring?

I want to consume rest api from url with http basic authentication that returns a big json & then i want to parse that json without POJO to get some values out of it. How can i achieve that in java spring?
I know this is common question but i could not get proper solution that worked for me.
Please help me someone.
Using the Apache HttpClient, the following Client Code snipped has been copied from the following URL. The comments have been added by myself.
https://www.baeldung.com/httpclient-4-basic-authentication
HttpGet request = new HttpGet(URL_SECURED_BY_BASIC_AUTHENTICATION);
// Combine the user and password pair into the right format
String auth = DEFAULT_USER + ":" + DEFAULT_PASS;
// Encode the user-password pair string in Base64
byte[] encodedAuth = Base64.encodeBase64(
auth.getBytes(StandardCharsets.ISO_8859_1));
// Build the header String "Basic [Base64 encoded String]"
String authHeader = "Basic " + new String(encodedAuth);
// Set the created header string as actual header in your request
request.setHeader(HttpHeaders.AUTHORIZATION, authHeader);
HttpClient client = HttpClientBuilder.create().build();
HttpResponse response = client.execute(request);
int statusCode = response.getStatusLine().getStatusCode();
assertThat(statusCode, equalTo(HttpStatus.SC_OK));

Google authorization access API via browser

I have a problem with my Google API.
I would like to avoid going through a browser to retrieve my access authorization.
I would like to retrieve the code directly into a variable.
This is the kind of URL that I sent :
https://accounts.google.com/o/oauth2/auth?response_type=code&client_id=2131233123321332&scope=https://www.googleapis.com/auth/admin.directory.group%20https://www.googleapis.com/auth/admin.directory.group.readonly&redirect_uri=https://tito.com
HttpClient httpclient = new DefaultHttpClient();
HttpGet httpget = new HttpGet("https://accounts.google.com/o/oauth2/auth?access_type=online&approval_prompt=auto&client_id=22fdgdfg40-1gmgdfggdps0hfol.apps.googleusercontent.com&redirect_uri=https://tito.com/&response_type=code&scope=https://www.googleapis.com/auth/admin.directory.group%20https://www.googleapis.com/auth/admin.directory.group.readonly");
HttpResponse responses = client.execute(httpget);
HttpParams param = responses.getParams();
responses.getParams().getParameter("code");
System.out.println(responses.getParams().getParameter("code"));
System.out.println("Response Code : " + responses.getStatusLine().getStatusCode());

HTTP post JSON java

I'm trying to post some json data using a http post method within my android application however i cannot seem to get it to work, the string is building fine and it works if i test using google chrome addon advanced rest client. I'm not the strongest with JSON hence why it is a string and not a JSON object. The Post request does not execute. Thanks in advance
String json = "{\"data\": [";
for (String tweet : tweetContent)
{
json = json + "{\"text\": \"" + tweet + "\", \"query\": \"" + SearchTerm + "\", \"topic\": \"movies\"},";
}
json = json.substring(0, json.length() - 1);
json = json + "]}";
Log.i("matt", json);
// Create a new HttpClient and Post Header
HttpClient httpclient = new DefaultHttpClient();
HttpPost httppost = new HttpPost("http://www.sentiment140.com/api/bulkClassifyJson?appid=matt-43#hotmail.com");
StringEntity entity = new StringEntity(json, HTTP.UTF_8);
httppost.setEntity(entity);
// Execute HTTP Post Request
HttpResponse response = httpclient.execute(httppost);
String responseBody = EntityUtils.toString(response.getEntity());
Log.i(LOG_TAG, responseBody);
sentiments.add(responseBody.toString());
what is the response code that you are getting back after posting from the Http client.
It should be 200 for a successful Http post. Other wise there is some issue.
You are posting the JSON data to the URL. which application is reading this data from the URL. Is there some servlet on the other application that is reading JSON data fromrequest. check that and see.
Also check the request headers for the Http Post request. if you are setting all the request headers properly.

How to pass xml in POST method?

I have to pass xml in a request, but I cannot figure out how can I perform it :/. Can you please help me?
I've already stored and prepared the xml.
The request sample:
POST http://..... HTTP/1.0
Content-type: text/xml
and xml
Thanks in advance
What is the source and destination of your xml?
If your source is say a file, and your destination is say a servlet, you can use curl http://en.wikipedia.org/wiki/CURL to send the xml and a servlet to receive it.
The servlet 3.0 spec has new features for this kind of stuff so that should make it easy.
OR
Are you trying to send a post from your java application?
John : )
Use HttpClient
Following is the code I use to post xml to a server.
String payload = <XML String>
HttpPost post = new HttpPost("http://" + ip + ":" + port);
LOGGER.info("WebService Call for " + ip + ":" + port);
try {
StringEntity entity = new StringEntity(payload);
post.setEntity(entity);
HttpResponse response = httpClient.execute(post);
HttpEntity resEntity = response.getEntity();
EntityUtils.consume(resEntity);
} finally {
post.releaseConnection();
}

Android HTTPGet to Rails REST Login

I have a login that needs an email and password.
If I hit it from Postman rest client with this:
www.site.com/login.json?session[email]=bob#gmail.com&session[password]=password
The server (Rails) will read it just fine, like this:
{"session"=>{"email"=>"bob#gmail.com", "password"=>"password"}, "action"=>"create", "controller"=>"sessions", "format"=>"json"}
But, if I send in the same thing with HTTPGet from android, like this:
HttpClient httpclient = new DefaultHttpClient();
//get the parameters
String email = params[0];
String password = params[1];
String url = "http://www.site.com/login.json?session[email]=" + email + "?session[password]=" + password;
HttpGet httpget = new HttpGet(url);
httpget.setHeader("Accept", "application/json");
httpget.setHeader("Content-type", "application/json");
response = httpclient.execute(httpget);
The server doesn't recognize the parameters, and I end up with an empty json object like this:
{"session"=>{}, "action"=>"create", "controller"=>"sessions", "format"=>"json"}
Anybody know how to form the parameters in this HTTPGet call in android to work like it will in a the rest client call? Thanks!
It seems you have a typo in URL and params get messed up. This line:
String url = "http://www.site.com/login.json?session[email]=" + email + "?session[password]=" + password;
should be
String url = "http://www.site.com/login.json?session[email]=" + email + "&session[password]=" + password;
Note that I've replaced ?session[password]= with &session[password]=.
Do you need to send USER-AGENT or other HTTP headers for it to be valid? Did you trace the HTTP connection with Fiddler2 or another HTTP trace? That ? instead of a & is probably it though.
For a type-safe REST client for Android try: http://square.github.io/retrofit/ It works very nice and you don't have to worry about manual parsing.
One thought I have is that you could try encoding the query string of your URL.
String query = URLEncoder.encode("session[email]=" + email + "?session[password]=" + password", "UTF-8");
String url = "http://www.site.com/login.json?" + query;
HttpGet httpget = new HttpGet(url);
....
* Replace the ?session in the URL with &session as its a mistake..
If the issue still persists, then try using a POST request as:
- in the first place exposing the email and password that way isn't safe practice
- and POST variables can be easily be handled in Rails controllers using the params tag eg. params[:tag] where tag is the key in the Json object.

Categories

Resources