Trying to put JSON request in HTTPGet on android - android

The api my app is working with is expecting a GET request for search results that looks like this:
Method: GET
Headers:
{
"Content-Type": "application/json",
"X-AUTHORIZATION": "8eb40dba2f0c6d7de8b9c6e1865aa507"
}
Request:
{
"keyword": "X S"
}
Response:
{
"status": "success",
"code": 0,
"meta": {
"exec_time": 0.012183904647827
},
"message": "",
"data": [
]
}
I have a class called HttpGetWithEntity that i found online that looks like this:
public class HttpGetWithEntity extends HttpEntityEnclosingRequestBase {
public HttpGetWithEntity() {
super();
}
public HttpGetWithEntity(URI uri) {
super();
setURI(uri);
}
public HttpGetWithEntity(String uri) {
super();
setURI(URI.create(uri));
}
#Override
public String getMethod() {
return HttpGet.METHOD_NAME;
}
}
and i am implementing it like so:
public HttpResponse invokeXAUTHGETJsonService(String url, String token,
String jsonPost) {
Log.v("KEYWORD", "KEYWORD GOING UP:"+jsonPost);
HttpParams params = new BasicHttpParams();
HttpResponse response = null;
try {
HttpGetWithEntity request = new HttpGetWithEntity(url);
Log.v("UPU", "URL:" + url +" token:"+token);
request.setHeader("X-AUTHORIZATION", token);
request.setHeader("Accept", "application/json");
request.addHeader("Content-Type", "application/json");
StringEntity se = new StringEntity(jsonPost);
request.setEntity(se);
response = client.execute(request);
} catch (ClientProtocolException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
return response;
}
My log to check the json i am posting looks like this:
03-09 14:38:01.034: V/KEYWORD(11739): KEYWORD CREATED: {"keyword":"e"}
The problem is, it seems like the JSON never reaches the api or is ignored. Does anyone know what i am doing wrong..
thanks

GET method will not send the request.entity to the server..
instead of using "request.setEntity() .."
just access the parms of the request setting " "keyword": "X S"" as parm K-V pair and append them to the url that you are GETTING:
domain/path?keyword=X%20S
do not use the entity unless you are POST or PUT method.

Related

Android Volly Parsing Error for Nested JSONObject

I am trying to post Json data via Android Volly library but getting an error.
Here is my Json body which perfectly working with Postman.
{
"fullName": "Mr X",
"fatherName": "Mr Y",
"motherName": "Mrs Z",
"nidNo": "34345",
"surveyDate": "2020-03-25",
"birthCertificateNo": "3435355",
"mobileNumber": "01834261758",
"dateOfBirth": "",
"gender": "Male",
"bloodGroup": "A+",
"numOfDaysSick": "23",
"numOfContInftPerson": "0",
"remarks": "Need Rest",
"physicalSymptoms": ",Runny nose,Sore throat",
"status": "User",
"isForeignVisitor": "false",
"isRead": "false",
"presentAddress": {
"village": "Sonapur",
"postOffice": "Noahat",
"postCode": "1219",
"upazila": "Sonaimuri",
"district": "Noakhali",
"division": "Chittagong"
},
"permanentAddress": {
"village": "Sonapur",
"postOffice": "Noahat",
"postCode": "1234",
"upazila": "Sonaimuri",
"district": "Noakhali",
"division": "Chittagong"
}}
But when i try to send it via Android Volly's Post call I am getting the error below :
com.android.volley.ParseError: org.json.JSONException: Value Survey of type java.lang.String cannot be converted to JSONObject
Here is my Android method to generate this Json body.
Note that : I can successfully generate Json body with this Android method and copy paste(from Logcat) to Postman, it works fine. But Android Volly giving me such error. My url is also ok because I tested it manually.
public void SendSurveyDataToServer(){
customProgressBar.show();
//--
//-------------------------------
JSONObject permanent_address = new JSONObject();
try {
permanent_address.put("village", village_pS);
permanent_address.put("postOffice", post_office_pS);
permanent_address.put("postCode", post_code_pS);
permanent_address.put("upazila", upazilla_pS);
permanent_address.put("district", district_pS);
permanent_address.put("division", division_pS);
} catch (JSONException e) {
e.printStackTrace();
}
//--
JSONObject present_address = new JSONObject();
try {
present_address.put("village", village_tS);
present_address.put("postOffice", post_office_tS);
present_address.put("postCode", post_code_tS);
present_address.put("upazila", upazilla_tS);
present_address.put("district", district_tS);
present_address.put("division", division_tS);
} catch (JSONException e) {
e.printStackTrace();
}
//--
if(numberofContactedPersonS.equals("Yes")){
numberofContactedPersonS = "true";
}else{
numberofContactedPersonS = "false";
}
//--
//--
JSONObject parameters = new JSONObject();
try {
parameters.put("fullName", fullNameS);
parameters.put("fatherName", fatherNameS);
parameters.put("motherName", motherNameS);
parameters.put("nidNo", nidNoS);
parameters.put("surveyDate", "2020-03-25");
parameters.put("birthCertificateNo", birthdayCertificateNoS);
parameters.put("mobileNumber", mobileNoS);
parameters.put("dateOfBirth", "");
parameters.put("gender", gender_selectS);
parameters.put("bloodGroup", blood_group_selectS);
parameters.put("numOfDaysSick", sickDaysNoS);
parameters.put("numOfContInftPerson", "0");
parameters.put("remarks", remarksS);
parameters.put("physicalSymptoms", physicalSymptomsS);
parameters.put("status", statusS);
parameters.put("isForeignVisitor", numberofContactedPersonS );
parameters.put("isRead", "false");
parameters.put("presentAddress", present_address);
parameters.put("permanentAddress", permanent_address);
} catch (JSONException e) {
e.printStackTrace();
}
Log.d(classTag,parameters.toString());
RequestQueue rq = Volley.newRequestQueue(this);
JsonObjectRequest jsonObjectRequest = new JsonObjectRequest
(Request.Method.POST, ApiClass.server_path+ApiClass.saveSurvey, parameters, new Response.Listener<JSONObject>() {
#Override
public void onResponse(JSONObject response) {
String respo=response.toString();
Log.d(classTag,respo);
//iosDialog.cancel();
//Parse_signup_data(respo);
Log.e(classTag,respo);
if(respo.equalsIgnoreCase("Survey Info save Successfully")){
Toast.makeText(Survey.this,"Your survey submitted successfully. Thank you!",Toast.LENGTH_LONG).show();
//----------------------------------------
}else if(respo.equalsIgnoreCase("Survey Info already exits")){
Toast.makeText(Survey.this,"Survey info already exist with this NID and Birth Certificate Number!",Toast.LENGTH_LONG).show();
}else{
Toast.makeText(Survey.this,"There is an error while submitting your survey, please try again!",Toast.LENGTH_LONG).show();
Log.e(classTag,"There is an error while submitting your survey, please try again!");
}
customProgressBar.hide();
}
}, new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
// TODO: Handle error
// Toast.makeText(MainActivity.this,"Can't connect with server! Please check your network connection.",Toast.LENGTH_LONG).show();
customProgressBar.hide();
Log.d(classTag,error.toString());
}
});
jsonObjectRequest.setRetryPolicy(new DefaultRetryPolicy(30000,
DefaultRetryPolicy.DEFAULT_MAX_RETRIES,
DefaultRetryPolicy.DEFAULT_BACKOFF_MULT));
rq.getCache().clear();
rq.add(jsonObjectRequest);
//--------------
}
After searching for 3 days I found that the problem is API response. It was giving me 'Success' and 'Failed' in byte format but I was always checking the response for JSONObject or at least String. Postman converted the byte data into string automatically and showed me, for that reason I thought server was giving me the response in string format.
However, I sent the Json request by Volly's String Request and track the response. Then I found what is messing with me! Our backend developer might be lazy to give a response in String or Json format.
I got the response by converting byte to string :
String string = new String(response.data, StandardCharsets.UTF_8);
Here is my modification for this :
RequestQueue requestQueue = Volley.newRequestQueue(this);
String URL = ApiClass.server_path+ApiClass.saveSurvey;
final String requestBody = parameters.toString();
StringRequest stringRequest = new StringRequest(Request.Method.POST, URL, new Response.Listener<String>() {
#Override
public void onResponse(String response) {
Log.i("VOLLEY", response);
customProgressBar.hide();
}
}, new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
Log.e("VOLLEY", error.toString());
customProgressBar.hide();
}
}) {
#Override
public String getBodyContentType() {
return "application/json; charset=utf-8";
}
#Override
public byte[] getBody() throws AuthFailureError {
try {
return requestBody == null ? null : requestBody.getBytes("utf-8");
} catch (UnsupportedEncodingException uee) {
VolleyLog.wtf("Unsupported Encoding while trying to get the bytes of %s using %s", requestBody, "utf-8");
return null;
}
}
#Override
protected Response<String> parseNetworkResponse(NetworkResponse response) {
//customProgressBar.hide();
if (android.os.Build.VERSION.SDK_INT >= android.os.Build.VERSION_CODES.KITKAT) {
String string = new String(response.data, StandardCharsets.UTF_8);
Log.e(classTag,string);
serverMsg = string;
showServerMsgNow = true;
Log.e(classTag,"Server msg : "+serverMsg+" server show : "+showServerMsgNow);
// ShowServerResponse();
}
String responseString = "";
if (response != null) {
responseString = String.valueOf(response.statusCode);
// can get more details such as response.headers
}
return Response.success(responseString, HttpHeaderParser.parseCacheHeaders(response));
}
};
requestQueue.add(stringRequest);

Android - Volley library: Session expired issue in SSL production environment

I had 2 pages: first one is login page and second is category page. In login API after entering the credentials, I am getting the response as sesssion id from response header.
The sesssion id will be saved and it will use for further API calls. I am trying to call second API (category page). In this page, as an input am passing the saved session id in the request header. Getting response as "session expired". Also tried to pass Set-Cookie: PHPSESSID=d9f9sdkfjs9 in the request header. but it didn't work.
Note :
I am experiencing this issue in production environment only (SSL included)
I am using volley library for handling APIs.
public void fnCallLoginAPI() {
try {
//DEMO URL
//final String URL="http://demo.io/api/api.php?m=login";
//LIVE URL
final String URL = "https://www.live.com/shop/api/api.php?m=login";
final String requestBody = "email=abc.b#xyz.com" + "&password=43443==" + "&strPlatform=i" + "&strDeviceToken=null";
StringRequest stringRequest = new StringRequest(Request.Method.POST, URL, new Response.Listener<String>() {
#Override
public void onResponse(String response) {
String strResponse = response;
System.out.println("THE RESPONSE IS in PROFILE IS" + response);
}
},
new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
}
})
{
#Override
public Map<String, String> getHeaders() throws AuthFailureError {
Map<String, String> headers = new HashMap<>();
headers.put("Cookie", "PHPSESSID=" + sessionID);
return headers;
}
#Override
public byte[] getBody() throws AuthFailureError {
byte[] body = new byte[0];
try {
System.out.println("THE REQIEST BODY IS" + requestBody);
body = requestBody.getBytes("UTF-8");
} catch (UnsupportedEncodingException e) {
Log.e("TAG", "Unable to gets bytes from JSON", e.fillInStackTrace());
}
return body;
}
};
AppApplication.getInstance().addToRequestQueue(stringRequest, "assignment");
} catch (Exception e) {
}
}
public void fnCallCateGoryAPI(){
try { final String URL ="https://www.live.com/shop/api/api.php?m=getcategories";
StringRequest stringRequest = new StringRequest(Request.Method.POST, URL, new Response.Listener<String>() {
#Override
public void onResponse(String response) {
String strResponse = response;
System.out.println("THE RESPONSE IS in PROFILE IS" + response);
JSONObject jsonObj = null;
try {
jsonObj = new JSONObject(strResponse);
sessionID = jsonObj.optString("session_id");
System.out.print("sessionID" + sessionID);
} catch (JSONException e) {
e.printStackTrace();
}
}
},
new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
}
})
{
};
AppApplication.getInstance().addToRequestQueue(stringRequest, "assignment");
} catch (Exception e) {}
}}
#fazil try after increasing the token expiration time from the backend
#fazil : I was facing something similar in my projects too and the reason i understood was actually due to multiple header values set under same key "Set-Cookie".
Please do check this in your logs.
Also, make sure that you have set the headers properly in your request(check the logs of request and response from your Server).
If everything implemented is correct and the issue is due to multiple values in the same header you need to check this implementation of volley : https://github.com/georgiecasey/android-volley-duplicateheadersfix

Getting improper response for Json webservice

I am using okhttp library for Json parsing.
I have created my AsyncTask as below for my Login Webservice :
class LoginAsyncTask extends AsyncTask<Void, Void, Void> {
private ProgressDialog dialog;
private String mstrLoginResponse="";
#Override
protected void onPreExecute() {
super.onPreExecute();
try {
dialog = new ProgressDialog(SignInActivity.this);
dialog.requestWindowFeature(Window.FEATURE_NO_TITLE);
dialog.getWindow().setBackgroundDrawable(new ColorDrawable(android.graphics.Color.TRANSPARENT));
dialog.setCancelable(false);
if (!dialog.isShowing()) {
dialog.show();
}
} catch (Exception e) {
e.printStackTrace();
}
}
#Override
protected Void doInBackground(Void... params) {
try {
RequestBody formBody = new FormEncodingBuilder()
.add("mobile_number", strPhone)
.add("password", strPassword)
.build();
mstrLoginResponse = HttpUtils.postRun("login", formBody);
Constant.displayLogE(">>>TT : ",""+mstrLoginResponse);
} catch (Exception e) {
e.printStackTrace();
}
return null;
}
#Override
protected void onPostExecute(Void aVoid) {
super.onPostExecute(aVoid);
if (dialog.isShowing()) {
dialog.dismiss();
}
if (mstrLoginResponse != null) {
try {
JSONObject jsonRegister = new JSONObject(mstrLoginResponse);
int strLoginStatus = jsonRegister.getInt("status");
String strMessage = jsonRegister.getString("message");
if (strLoginStatus == 1) {
JSONObject jsonUserId = jsonRegister.getJSONObject("data");
String strUserId = jsonUserId.getString("user_id");
AppSettings.setPref(SignInActivity.this, USER_ID, String.valueOf(strUserId));
startActivity(new Intent(SignInActivity.this, MainActivity.class));
finish();
Constant.displayToast(SignInActivity.this, "" + strMessage);
} else {
ApiUtils.showAlertDialogue(SignInActivity.this, "" + strMessage);
}
} catch (Exception e) {
e.printStackTrace();
}
}
}
}
But, Unfortunetly getting below response :
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="utf-8">
<title>404 Page Not Found</title>
<style type="text/css">
::selection { background-color: #E13300; color: white; }
::-moz-selection { background-color: #E13300; color: white; }
and Exeption : org.json.JSONException: Value <!DOCTYPE of type java.lang.String cannot be converted to JSONObject
06-24 00:41:03.314 349-349/com.roadysmart W/System.err: at org.json.JSON.typeMismatch(JSON.java:111)
I am getting proper response in Postman.
My HttpUtils class is as below : `
public class HttpUtils {
/*public static final MediaType JSON
= MediaType.parse("application/json; charset=utf-8");*/
public static String BASE_URL = "http://temp.in/projects/temp/";
public static OkHttpClient client = new OkHttpClient();
public static String getRun(String url) throws IOException {
Log.d("URL===>", url);
Request request = new Request.Builder()
.url(url)
.build();
Response response = client.newCall(request).execute();
return response.body().string();
}
public static String postRun(String type, RequestBody formBody) throws IOException {
String str = "";
Request request = new Request.Builder()
.url(BASE_URL)
.post(formBody)
.build();
Response response = client.newCall(request).execute();
return response.body().string();
}
}
What might be the mistake ? Please, Help .
===>>EDIT :
Getting Proper response in postman as below :
{
"status": 1,
"message": "Login successful",
"data": {
"name": "subhu",
"mobile_number": "7777777777",
"email": "bhargavmodi777#gmail.com",
"user_id": "20"
}
}
Your response - <title>404 Page Not Found</title> tells me that your endpoint doesn't exist because you entered it incorrectly or the server is simply not running.
That exception you posted relates to the same issue, it can't parse the JSON because what the web call received was not application/json and instead just raw HTML.
Exeption : org.json.JSONException: Value <!DOCTYPE of type java.lang.String cannot
With that said, public static String BASE_URL = "http://temp.in/projects/temp/"; looks like a bad URL. Here is what I recommend:
First manually load that URL in your browser, you will notice the same HTML your client call received, will be presented to you.
Make sure you are running your server/service or whatever it is that responds to your request. You say Postman works, what parameters did you use? What are you communicating with?
If PostMan works, and postman runs from your computer, your computer is connected to your local network I presume. Is your Android device on the local network as well? Or are you on cell service (3G/LTE). If you are then your endpoint can't be reached unless you are connected to a VPN or something.

How to send SMS using Twilio in my android application?

In my android application I have created one button, when I had pressed on the button I want to send message.So for that I have created one java class and written twilio code.
final TwilioRestClient client = new TwilioRestClient(
ACCOUNT_SID, AUTH_TOKEN);
// Get the main account (The one we used to authenticate the
// client)
final Account mainAccount = client.getAccount();
final SmsFactory messageFactory = mainAccount.getSmsFactory();
final Map<String, String> messageParams = new HashMap<String, String>();
messageParams.put("To", "+912342423423");
messageParams.put("From", "+132432432434");
messageParams.put("Body", "This is my message");
try {
messageFactory.create(messageParams);
} catch (TwilioRestException e) {
e.printStackTrace();
}
when I am using the above code it showing some error like java.lang.NoSuchMethodError: org.apache.http.impl.conn.tsccm.ThreadSafeClientConnManager
I have added only one jar file in lib folder as " twilio-java-sdk-3.3.10-jar-with-dependencies.jar ".
please tell me what can I do?
I have used HttpPost method to send sms in that i have passed my url with base authentication here is my code
HttpClient httpclient = new DefaultHttpClient();
HttpPost httppost = new HttpPost(
"https://api.twilio.com/2010-04-01/Accounts/{ACCOUNT_SID}/SMS/Messages");
String base64EncodedCredentials = "Basic "
+ Base64.encodeToString(
(ACCOUNT_SID + ":" + AUTH_TOKEN).getBytes(),
Base64.NO_WRAP);
httppost.setHeader("Authorization",
base64EncodedCredentials);
try {
List<NameValuePair> nameValuePairs = new ArrayList<NameValuePair>();
nameValuePairs.add(new BasicNameValuePair("From",
"+123424353534"));
nameValuePairs.add(new BasicNameValuePair("To",
"+914342423434"));
nameValuePairs.add(new BasicNameValuePair("Body",
"Welcome to Twilio"));
httppost.setEntity(new UrlEncodedFormEntity(
nameValuePairs));
// Execute HTTP Post Request
HttpResponse response = httpclient.execute(httppost);
HttpEntity entity = response.getEntity();
System.out.println("Entity post is: "
+ EntityUtils.toString(entity));
} catch (ClientProtocolException e) {
} catch (IOException e) {
}
}
It is working well.
This solution with Retrofit
public static final String ACCOUNT_SID = "accountSId";
public static final String AUTH_TOKEN = "authToken";
private void sendMessage() {
String body = "Hello test";
String from = "+...";
String to = "+...";
String base64EncodedCredentials = "Basic " + Base64.encodeToString(
(ACCOUNT_SID + ":" + AUTH_TOKEN).getBytes(), Base64.NO_WRAP
);
Map<String, String> data = new HashMap<>();
data.put("From", from);
data.put("To", to);
data.put("Body", body);
Retrofit retrofit = new Retrofit.Builder()
.baseUrl("https://api.twilio.com/2010-04-01/")
.build();
TwilioApi api = retrofit.create(TwilioApi.class);
api.sendMessage(ACCOUNT_SID, base64EncodedCredentials, data).enqueue(new Callback<ResponseBody>() {
#Override
public void onResponse(Call<ResponseBody> call, Response<ResponseBody> response) {
if (response.isSuccessful()) Log.d("TAG", "onResponse->success");
else Log.d("TAG", "onResponse->failure");
}
#Override
public void onFailure(Call<ResponseBody> call, Throwable t) {
Log.d("TAG", "onFailure");
}
});
}
interface TwilioApi {
#FormUrlEncoded
#POST("Accounts/{ACCOUNT_SID}/SMS/Messages")
Call<ResponseBody> sendMessage(
#Path("ACCOUNT_SID") String accountSId,
#Header("Authorization") String signature,
#FieldMap Map<String, String> metadata
);
}
Dependencies for build.gradle
compile 'com.squareup.retrofit2:retrofit:2.1.0'
My method, using OkHttp:
1. Prerequisites
Gradle:
dependencies {
compile 'com.squareup.okhttp3:okhttp:3.4.1'
}
Manifest:
<uses-permission android:name="android.permission.INTERNET"/>
Permission in activity:
if (android.os.Build.VERSION.SDK_INT > 9) {
StrictMode.setThreadPolicy( new StrictMode.ThreadPolicy.Builder().permitAll().build() );
}
2. Code
private void sendSms(String toPhoneNumber, String message){
OkHttpClient client = new OkHttpClient();
String url = "https://api.twilio.com/2010-04-01/Accounts/"+ACCOUNT_SID+"/SMS/Messages";
String base64EncodedCredentials = "Basic " + Base64.encodeToString((ACCOUNT_SID + ":" + AUTH_TOKEN).getBytes(), Base64.NO_WRAP);
RequestBody body = new FormBody.Builder()
.add("From", fromPhoneNumber)
.add("To", toPhoneNumber)
.add("Body", message)
.build();
Request request = new Request.Builder()
.url(url)
.post(body)
.header("Authorization", base64EncodedCredentials)
.build();
try {
Response response = client.newCall(request).execute();
Log.d(TAG, "sendSms: "+ response.body().string());
} catch (IOException e) { e.printStackTrace(); }
}
I used Allu code for generathing authorization in header
Twilio Java SDK has third party dependencies without them it is not going to work. The dependencies are:
1. Httpcore
2. Httpclient
3. Commons lang
4. Json simple
5. Jackson
Not quite sure if you need them all, but at least now you are missing httpcore
You should use the BasicPhone project of Twilio SDK. I've tried this to call and now I can call too. This project has all the methods and functions that you need to call and to send SMS. First of all, you need a PHP web service to get capability token and pass that PHP script into your app.
This is how I solved my need.
public class TwilioAsyncTask extends AsyncTask {
Context context;
ProgressDialog progressDialog;
public TwilioAsyncTask(Context context) {
this.context = context;
}
#Override
protected String doInBackground(String... strings) {
//
HttpClient httpclient = new DefaultHttpClient();
HttpPost httppost = new HttpPost(
"https://api.twilio.com/2010-04-01/Accounts/AC_yourACCOUNT_SID_9b/SMS/Messages");
String base64EncodedCredentials = "Basic "
+ Base64.encodeToString(
(ACCOUNT_SID + ":" + AUTH_TOKEN).getBytes(),
Base64.NO_WRAP);
httppost.setHeader("Authorization",
base64EncodedCredentials);
try {
int randomPIN = (int) (Math.random() * 9000) + 1000;
String randomVeriValue = "" + randomPIN;
// these are for control in other anctivity used sharepreference
editorTwilio.putString("twilio_veri_no", randomVeriValue);
editorTwilio.commit();
List<NameValuePair> nameValuePairs = new ArrayList<NameValuePair>();
nameValuePairs.add(new BasicNameValuePair("From",
"+148******")); // what number they gave you
nameValuePairs.add(new BasicNameValuePair("To",
"+90" + phoneNo)); // your phone or our customers
nameValuePairs.add(new BasicNameValuePair("Body",
"Your verification number is : " + randomVeriValue));
httppost.setEntity(new UrlEncodedFormEntity(
nameValuePairs));
// Execute HTTP Post Request
HttpResponse response = httpclient.execute(httppost);
HttpEntity entity = response.getEntity();
System.out.println("Entity post is: "
+ EntityUtils.toString(entity));
// Util.showMessage(mParentAct, "Welcome");
} catch (ClientProtocolException e) {
} catch (IOException e) {
}
//
return "Executed";
}
#Override
protected void onPostExecute(String result) {
// execution of result of Long time consuming operation
//progressDialog.dismiss();
}
#Override
protected void onPreExecute() {
progressDialog = ProgressDialog.show(context, "", " Wait for ");
}
#Override
protected void onProgressUpdate(String... text) {
// Things to be done while execution of long running operation is in
// progress. For example updating ProgessDialog
}
}
And call your Task
TwilioAsyncTask task = new TwilioAsyncTask(CountryAndPhone.this);
task.execute();

Correct way to generate an httprequest to mirror api service from android

i try to push a timeline card to the Glass from my android application. i use this code:
String BASE_URL = "https://www.googleapis.com/upload/mirror/v1/";
try {
final HttpPost request = new HttpPost();
request.setURI(new URI(BASE_URL + "timeline"));
request.addHeader("Authorization", String.format("Bearer %s", token));
request.addHeader("Content-Type", "application/json");
request.setEntity(new StringEntity(json.toString()));
// Execute the request on a background thread
mThreadPool.execute(new Runnable() {
#Override
public void run() {
try {
final HttpResponse response = mClient.execute(request);
if (response.getStatusLine().getStatusCode() == HttpStatus.SC_OK) {
mHandler.post(new Runnable() {
#Override
public void run() {
callback.onSuccess(response);
}
});
} else {
mHandler.post(new Runnable() {
#Override
public void run() {
callback.onFailure(response, null);
}
});
}
} catch (final IOException e) {
mHandler.post(new Runnable() {
#Override
public void run() {
callback.onFailure(null, e);
}
});
}
}
});
} catch (UnsupportedEncodingException e) {
// Note: This should never happen
} catch (URISyntaxException e) {
// Note: This should never happen
}
the json is like this :
{"notification":{"level":"DEFAULT"},"text":"Pizza and spaghetti"}
but the service respond with an error :
"error": {
"errors": [
{
"domain": "global",
"reason": "badContent",
"message": "Media type 'application/json' is not supported. Valid media types: [image/*, audio/*, video/*]"
}
],
"code": 400,
"message": "Media type 'application/json' is not supported. Valid media types: [image/*, audio/*, video/*]"
}
}
i follow the code from here: https://github.com/twaddington/mirror-quickstart-android
any idea?
Ps. there is another way to push a timeline card from an android application to the google glass?
Thanks
As you can see in the Google Docs (https://developers.google.com/glass/v1/reference/timeline/insert) this request only accept mutimedia data as 'Content-type'.
Try changing this line with the correct content type (image/, audio/, video/*) : request.addHeader("Content-Type", "application/json");
You will have to add the multimedia object inside your HTTPost object. More info about that:
Sending images using Http Post
--EDIT--
The request you want to do (only metadata, without multimedia) has to be done to:
https://www.googleapis.com/mirror/v1/ (notice that there is not the upload word).

Categories

Resources