Sms cannot be Sent via twilio getting 400 error - twilio

I am trying to send SMS via Twilio using HttpEntity from my Java code. I am getting 400 Bad Request with no details. The response is below.
[<html>
<head><title>400 Bad Request</title></head>
<body>
<center><h1>400 Bad Request</h1></center>
<hr><center>openresty</center>
</body>
</html>]
Below is the code I have used to send a request. The request is successful from Postman. I cannot use Java SDK and has to use RestTemplate.
HttpHeaders headers = new HttpHeaders();
headers.setContentType(MediaType.APPLICATION_FORM_URLENCODED);
headers.add("route-to-back-end-endpoint", "https://api.twilio.com/2010-04-01/Accounts/xxx/Messages.json");
MultiValueMap<String, String> map = new LinkedMultiValueMap<>();
map.add("To", "+91*******");
map.add("From", "+1******");
map.add("Body", "Try try try");
HttpEntity<MultiValueMap<String, String>> entity = new HttpEntity<>(map, headers);
String response = null;
try {
restTemplateSsl.getInterceptors().add(new BasicAuthenticationInterceptor("xxx", "yyy"));
response = restTemplateSsl.postForObject("Internal Xml Gateway Link", entity, String.class);
} catch (Exception e) {
e.printStackTrace();
log.error("Exception : {} ", e.getMessage());
}
log.info("Response Received :{}", response);
return response;
The authentication is successful with Twilio. So no authentication issue. I am not sure what is exactly wrong in request.

You might get this error if the path in your HTTP request doesn't start with '/'.

Related

How to authenticate with HttpRepl to test protected api's?

In order to test the Azure DevOp API,
POST https://dev.azure.com/{organization}/{project}/_apis/git/repositories/{repositoryId}/itemsbatch?api-version=6.0
we need to log in first.
HTTP/1.1 203 Non-Authoritative Information
What is the best way to handle authentication in this API testing?
Add tokens in the request headers?
After you get JWT you can use it in the command line like below:
set header Authorization "bearer <TOKEN VALUE>"
You can see this link https://learn.microsoft.com/en-us/aspnet/core/web-api/http-repl/?view=aspnetcore-6.0&tabs=windows#set-http-request-headers
To test the REST API, you need either Testing Tool to drive the API or writing down your own code.
Rest API can be tested with tools like:
Advanced Rest Client
Postman
To write your own code, you could refer to the following sample:
public static async void GetProjects()
{
try
{
var personalaccesstoken = "PAT_FROM_WEBSITE";
using (HttpClient client = new HttpClient())
{
client.DefaultRequestHeaders.Accept.Add(
new System.Net.Http.Headers.MediaTypeWithQualityHeaderValue("application/json"));
client.DefaultRequestHeaders.Authorization = new AuthenticationHeaderValue("Basic",
Convert.ToBase64String(
System.Text.ASCIIEncoding.ASCII.GetBytes(
string.Format("{0}:{1}", "", personalaccesstoken))));
using (HttpResponseMessage response = await client.GetAsync(
"https://dev.azure.com/{organization}/_apis/projects"))
{
response.EnsureSuccessStatusCode();
string responseBody = await response.Content.ReadAsStringAsync();
Console.WriteLine(responseBody);
}
}
}
catch (Exception ex)
{
Console.WriteLine(ex.ToString());
}
}

Microsoft Graph API Authentication_MissingOrMalformed

I am using oauth2/token to authenticate my application and get the access_token. Bellow is the java code which is working fine.
private String getToken() throws Exception {
String access_token = "";
String url = "https://login.windows.net/MyApplication_ID_here/oauth2/token";
HttpClient client = HttpClients.createDefault();
HttpPost post = new HttpPost(url);
post.setHeader("Content-Type", "application/x-www-form-urlencoded");
List<NameValuePair> urlParameters = new ArrayList<NameValuePair>();
urlParameters.add(new BasicNameValuePair("grant_type", "client_credentials"));
urlParameters.add(new BasicNameValuePair("client_id", "MyApplication_ID_here"));
urlParameters.add(new BasicNameValuePair("client_secret", "MyApplication_secret_here"));
urlParameters.add(new BasicNameValuePair("resource", "https://graph.microsoft.com"));
post.setEntity(new UrlEncodedFormEntity(urlParameters));
HttpResponse response = client.execute(post);
System.out.println("Sending 'POST' request to URL : " + url);
System.out.println("Post parameters : " + post.getEntity());
System.out.println("Response Code : " + response.getStatusLine().getStatusCode());
String responseAsString = EntityUtils.toString(response.getEntity());
System.out.println(responseAsString);
try {
access_token = responseAsString.split(",")[6].split("\"")[3]; // get the access_token from response
} catch (Exception e) {
e.printStackTrace();
return null;
}
return access_token;
}
Response :
{"token_type":"Bearer","expires_in":"3599","ext_expires_in":"0","expires_on":"1493011626","not_before":"1493007726","resource":"https://graph.microsoft.com","access_token":"eyJ0e..."}
then I am using access_token to load the memberOf value which is not working and gives me the Access Token missing or malformed error. Bellow is the java code
private void getMemberOf()
{
HttpClient httpclient = HttpClients.createDefault();
try
{
URIBuilder builder = new URIBuilder("https://graph.windows.net/MyApplication_ID_here/users/test#testABC.onmicrosoft.com/memberOf?api-version=1.6");
URI uri = builder.build();
HttpGet request = new HttpGet(uri);
request.addHeader("Authorization", "Bearer " + access_token);
request.addHeader("Content-Type", "application/json");
HttpResponse response = httpclient.execute(request);
HttpEntity entity = response.getEntity();
System.out.println("Response Code : " + response.getStatusLine().getStatusCode());
if (entity != null) {
System.out.println(EntityUtils.toString(entity));
}
}
catch (Exception e)
{
e.getMessage();
}
}
Response :
Response Code : 401
{"odata.error":{"code":"Authentication_MissingOrMalformed","message":{"lang":"en","value":"Access Token missing or malformed."},"date":"2017-04-24T04:39:38","requestId":"c5aa2abe-9b37-4611-8db1-107e3ec08c14","values":null}}
Can someone please tell me which part of the above request is wrong? Am I not setting access_token correctly?
According to your code , your access token is for resource "https://graph.microsoft.com"(Microsoft Graph API) ,But the access token is used for "https://graph.windows.net"(AAD Graph API) :
URIBuilder builder = new URIBuilder("https://graph.windows.net/MyApplication_ID_here/users/test#testABC.onmicrosoft.com/memberOf?api-version=1.6");
If you want to call Azure AD graph api , you need to get access token for Azure AD Graph API .
I got this issue while performing the CRUD operation on Azure AD B2C service via AD Graph API for user management.
The idea is to get the access token for the resource "graph.windows.net" instead I was using my tenant App Id URI as it was suggested here.
*might help people who faced the same issue and landed up here

How to get access_token of Exact Online API using apache OAuth 2.0

We are trying to use Exact Online API. It is using Apache OAuth 2.0 framework. For that we followed the below document.
https://developers.exactonline.com/#OAuth_Tutorial.html%3FTocPath%3DAuthentication%7C_____2
I successfully able to get the authorization code but failing to get the access_token with exception like below.
OAuthProblemException{error='invalid_request', description='Missing parameters: access_token', uri='null', state='null', scope='null', redirectUri='null', responseStatus=0, parameters={}}
My code is like this.
protected void processRequest(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
PrintWriter out = response.getWriter();
try {
OAuthAuthzResponse oar = OAuthAuthzResponse.oauthCodeAuthzResponse(request);
String code = oar.getCode();
OAuthClientRequest oAuthrequest = OAuthClientRequest
.tokenLocation("https://start.exactonline.co.uk/api/oauth2/token")
.setGrantType(GrantType.AUTHORIZATION_CODE)
.setClientId("my client id")
.setClientSecret("my client secret")
.setRedirectURI("http://localhost:8080/SampleServlet/AuthServlet")
.setCode(code)
.buildBodyMessage();
OAuthClient oAuthClient = new OAuthClient(new URLConnectionClient());
GitHubTokenResponse oAuthResponse = oAuthClient.accessToken(oAuthrequest, "POST",GitHubTokenResponse.class);
out.println("Access Token = " + oAuthResponse.getAccessToken());
} catch (OAuthSystemException ex) {
Logger.getLogger(AuthServlet.class.getName()).log(Level.SEVERE, null, ex);
} catch (OAuthProblemException ex) {
Logger.getLogger(AuthServlet.class.getName()).log(Level.SEVERE, null, ex);
} finally {
out.close();
}
}
Can some one please help me to sort this out.
Finally i resolved this issue with a simple change. The problem is with the line
GitHubTokenResponse oAuthResponse = oAuthClient.accessToken(oAuthrequest, "POST",GitHubTokenResponse.class);
Instead of this we have to use either of the below lines to get the access token properly.
OAuthJSONAccessTokenResponse oAuthResponse = oAuthClient.accessToken(oAuthrequest, OAuth.HttpMethod.POST);
(Or)
OAuthAccessTokenResponse oAuthResponse =oAuthClient.accessToken(oAuthrequest,OAuth.HttpMethod.POST);

Cant connect to survey monkey API

I am trying to connect to the survey monekey API with this code, which is not working. It says "Invalid API key" even though I got the API from the API console.
public void fetch() {
String url = "https://api.surveymonkey.net/v2/surveys/get_survey_list?api_key=" + apiKey;
System.out.println("request being sent");
System.out.println(url);
JSONObject obj = new JSONObject();
try {
// byte[] postDataBytes = obj.toJSONString().getBytes("UTF-8");
URL ourl = new URL(url.toString());
HttpURLConnection conn = (HttpURLConnection) ourl.openConnection();
conn.setDoOutput(true);
conn.setRequestMethod("POST");
conn.setRequestProperty("Authorization", "bearer " + accessToken);
conn.setRequestProperty("Content-Type", "application/json");
conn.getRequestProperty(obj.toString().getBytes("UTF-8").toString());
int k = conn.getResponseCode();
System.out.println("The response code received is " + k);
if (conn.getResponseCode() != 200) {
throw new RuntimeException("Failed : HTTP error code : "
+ conn.getResponseCode());
}
BufferedReader br = new BufferedReader(new InputStreamReader(
(conn.getInputStream())));
String output;
System.out.println("Output from Server .... \n");
output = br.readLine();
System.out.println(output);
} catch (MalformedURLException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
}
Here's the error:
request being sent
https://api.surveymonkey.net/v2/surveys/get_survey_list?api_key=---API-KEY----
The response code received is 200
Output from Server ....
{"status":3,"errmsg":"Expected object or value"}
I just got this url from the API console.
Ensure you are using the API key associated with your developer account registered at http://developer.surveymonkey.com, not the sample API key the console uses to let you try requests. The sample api key is not meant to be used with apps, only on the API console.
That particular error is generated when an empty string is sent for the POST data. The API expects an empty object at minimum ("{}"). If the issue pointed out by Miles above was just a typo (using 'getRequestProperty' instead of 'setRequestProperty',) check if toString on an empty JSONObject is returning "" or "{}".

Google play API returns error

i am getting the same issue as described in this post
. we have used almost exactly the same code. i have tried both with Client ID and Email address of the google service account in below mehotd
setServiceAccountId(GOOGLE_SERVICE_CLIENT_EMAIL) OR
setServiceAccountId(GOOGLE_CLIENT_ID)
error changes with the change in a/c id. if i use client id, error is
400 Bad Request { "error" : "invalid_grant" }
and if i use service email id, error is
401 Unauthorized {
"code" : 401, "errors" : [ {
"domain" : "androidpublisher",
"message" : "This developer account does not own the application.",
"reason" : "developerDoesNotOwnApplication" } ], "message" : "This developer account does not own the application." }
any idea?
There appears to be some evidence that Google Play API does not currently work with Service Accounts (madness). There is another thread on the issue here. You can read about the Google Service Accounts here. You can read about authentication for Android Google Play API here.
Once you have done the dance on the Google API Console to get a refresh_token you can get an access token like this:
private String getAccessToken()
{
HttpClient client = new DefaultHttpClient();
HttpPost post = new HttpPost("https://accounts.google.com/o/oauth2/token");
try
{
List<NameValuePair> nameValuePairs = new ArrayList<NameValuePair>(4);
nameValuePairs.add(new BasicNameValuePair("grant_type", "refresh_token"));
nameValuePairs.add(new BasicNameValuePair("client_id", "YOUR_CLIENT_ID);
nameValuePairs.add(new BasicNameValuePair("client_secret", "YOUR_CLIENT_SECRET"));
nameValuePairs.add(new BasicNameValuePair("refresh_token", "YOUR_REFRESH_TOKEN"));
post.setEntity(new UrlEncodedFormEntity(nameValuePairs));
HttpResponse response = client.execute(post);
BufferedReader reader = new BufferedReader(new InputStreamReader(response.getEntity().getContent()));
StringBuffer buffer = new StringBuffer();
for (String line = reader.readLine(); line != null; line = reader.readLine())
{
buffer.append(line);
}
JSONObject json = new JSONObject(buffer.toString());
return json.getString("access_token");
}
catch (IOException e) { e.printStackTrace(); }
catch (JSONException e) { e.printStackTrace(); }
return null;
}

Resources