I have tried all possible ways to get correct JSON response from the below microsoft health API url. But its always giving me the "Invalid Authorisation Request" in the JSON response. I have tried Base64 encoding of authorisation token also but its not responding. I don't know where i am going wrong ?
String authToken="EwCgAvF0BAAUkWhN6f8bO0+g89MA1fmZueWyRkQAAfO43zeEeKVHsQJ5DiKwK62uBH2Xxh5mkV9t0EnExHELbz3u/qeS0uTqOUL4dyc3QwDikXQvNwFXWyK7sj6ChM3NrIF9L+7mI0ecmBme8IcghJ+kU+4SxHWZkOrshA8g5XW+KliOJbKvu4bus+JiMYxwKnqkLW6hkVxGQ1EHf0HzkHTNnWMbr1T4vNWJos7ITalOorV455MGekOvhEaFETrma9lQfos0RPRbDhdaKJiNFxUYQCvVywlbxRm96AOHlm/Be7GKYgF+vyktNs4dPgPz2l9MlzSGSE0IXtamSCiCaUocLDQ9yMY+jxKA4VPqhvbr1z3rc7fMk/wJvYebxVsDZgAACEzG05vV/JrAcAGHT5EeXaixNgTOW+S7CMcp3qpJtcl6MKveXA1e3fgvSQPCHnsy9nDoWYMgk4Uv6UkMbirkyzlG2JMFVpLg9PJE6sHIO0BZlkMb/DWMudrEsR3dwz00H/zAru9u6jMHnrbb44C/1z5lyXgwB3jItd/SWmRUdCBu3rF8IBXglAeyHxH+Mj5Zt2l+2rqly0p2sSqoUwgi49kThIggSlmod932fLWATHx5Lx3BN/wGfWU9XQplphPwYQvBsRnwv+gcZi9eK07aDIcdGhcp9J1fwCkjnBTZw+f0mDOyEfUSCyD0pnRXwz5CYDVN94TfFgZdnFAwi5wslKNUOYh6QBAJzaSXS/nj376FsORdEA1mUgowb/I2npitlr7+NTN6S+qWMdpEuiOVDVydi3L0H+xXKOaagzrels7bN7RpK0C+/kUqLfFrg8SeXxinqd+qhADu+56pRJnh8Sn3qdx/FmTQ/iGSYnrMMlT6SRDUjNVFoS3F540B";
HttpClient client = new DefaultHttpClient();
HttpGet request = new HttpGet();
request.setURI(new URI("https://api.microsofthealth.net/v1/me/Summaries/Daily?startTime=" + startTime + "&endTime=" + endTime));
String authString = "Bearer " + authToken;
request.addHeader("Authorization", authString);
response = client.execute(request);
String json_string = EntityUtils.toString(response.getEntity());
I think you should check the access token again to make sure it's valid. Because I use the new token in your question, reponse still 401.
GET https://api.microsofthealth.net/v1/me/Profile/
Authorization: bearer EwCgAvF0BAAUkWhN6f8bO0+g89MA1fmZueWyRkQAAfO43zeEeKVHsQJ5DiKwK62uBH2Xxh5mkV9t0EnExHELbz3u/qeS0uTqOUL4dyc3QwDikXQvNwFXWyK7sj6ChM3NrIF9L+7mI0ecmBme8IcghJ+kU+4SxHWZkOrshA8g5XW+KliOJbKvu4bus+JiMYxwKnqkLW6hkVxGQ1EHf0HzkHTNnWMbr1T4vNWJos7ITalOorV455MGekOvhEaFETrma9lQfos0RPRbDhdaKJiNFxUYQCvVywlbxRm96AOHlm/Be7GKYgF+vyktNs4dPgPz2l9MlzSGSE0IXtamSCiCaUocLDQ9yMY+jxKA4VPqhvbr1z3rc7fMk/wJvYebxVsDZgAACEzG05vV/JrAcAGHT5EeXaixNgTOW+S7CMcp3qpJtcl6MKveXA1e3fgvSQPCHnsy9nDoWYMgk4Uv6UkMbirkyzlG2JMFVpLg9PJE6sHIO0BZlkMb/DWMudrEsR3dwz00H/zAru9u6jMHnrbb44C/1z5lyXgwB3jItd/SWmRUdCBu3rF8IBXglAeyHxH+Mj5Zt2l+2rqly0p2sSqoUwgi49kThIggSlmod932fLWATHx5Lx3BN/wGfWU9XQplphPwYQvBsRnwv+gcZi9eK07aDIcdGhcp9J1fwCkjnBTZw+f0mDOyEfUSCyD0pnRXwz5CYDVN94TfFgZdnFAwi5wslKNUOYh6QBAJzaSXS/nj376FsORdEA1mUgowb/I2npitlr7+NTN6S+qWMdpEuiOVDVydi3L0H+xXKOaagzrels7bN7RpK0C+/kUqLfFrg8SeXxinqd+qhADu+56pRJnh8Sn3qdx/FmTQ/iGSYnrMMlT6SRDUjNVFoS3F540B
-- response --
401 Unauthorized
Cache-Control: no-cache
Pragma: no-cache
Expires: -1
Server: Microsoft-IIS/8.5
WWW-Authenticate: Bearer realm="mshealth" error="invalid_token"
X-AspNet-Version: 4.0.30319
AppEx-Activity-Id: 7c22cdab-5307-4b62-b81b-42e1315d9b1b
x-powered-by: ASP.NET
Date: Mon, 31 Aug 2015 07:04:00 GMT
Content-Length: 0
Related
I am getting response body ** is
okhttp3.internal.http.RealResponseBody#6e33b4c How to convert this to json or string.
OkHttpClient client = new OkHttpClient();
Request request = new Request.Builder()
.url("https://mashape-community-urban-dictionary.p.rapidapi.com/define?term=check")
.get()
.addHeader("x-rapidapi-host", "mashape-community-urban-dictionary.p.rapidapi.com")
.addHeader("x-rapidapi-key", API)
.build();
Response response = client.newCall(request).execute();
Log.d("TAG", "response:toString() " + response.toString());
Log.d("TAG", "response:headers " + response.headers());
Log.d("TAG", "response:body " + response.body());
Log.d("TAG", "response:challenges " + response.challenges());
Log.d("TAG", "response:message " + response.message());
Log
response:toString() Response{protocol=http/1.1, code=200, message=OK, url=https://mashape-community-urban-dictionary.p.rapidapi.com/define?term=check}
response:headers Cache-Control: no-cache, no-store, must-revalidate
Content-Type: application/json; charset=utf-8
Date: Mon, 13 Apr 2020 11:03:35 GMT
Server: RapidAPI-1.1.0
Via: 1.1 google
X-License: http://api.urbandictionary.com/
X-RapidAPI-Region: AWS - ap-southeast-1
X-RapidAPI-Version: 1.1.0
Content-Length: 4386
Connection: keep-alive
response:body okhttp3.internal.http.RealResponseBody#6e33b4c
response:challenges []
response:message OK
in RAPID API DEVELOPER DASHBOARD, I CAN SEE RESPONSE BODY How to convert it to string or JSON?
This would get the list in JSON
JSONObject object = new JSONObject(response.body().string());
final JSONArray array = object.getJSONArray("list");
String url = "https://maps.googleapis.com/maps/api/distancematrix/json?origins="+expedTextView.getText().toString()+"&destinations="+destTextView.getText().toString()+"&sensor=false&mode=driving&key=AIzaSyC9BT3f2jmmPSJh2ewGfGiuVz1zeIfPX4A";
HttpClient httpClient = new DefaultHttpClient();
HttpContext localContext = new BasicHttpContext();
HttpGet httpGet = new HttpGet(url);
HttpResponse response = null;
try {
response = httpClient.execute(httpGet, localContext);
} catch (IOException e) {
e.printStackTrace();
}
Toast.makeText(SecondScreen.this, ""+response, Toast.LENGTH_LONG).show();
}
This is my code. I've tried to make an HTTP request suing this URL which constructs just fine, but, when I read the response, it doesn't look like JSON at all. Below is the code from response. Notice that the link works well when I put it in my browser.
HTTP/1.1 200 OK [Content-Type: application/json; charset=UTF-8, Date: Fri, 11 Jan 2019 14:26:57 GMT, Expires: Sat, 12 Jan 2019 14:26:57 GMT, Cache-Control: public, max-age=86400, Server: mafe, X-XSS-Protection: 1; mode=block, X-Frame-Options: SAMEORIGIN, Server-Timing: gfet4t7; dur=91, Alt-Svc: quic=":443"; ma=2592000; v="44,43,39,35", Accept-Ranges: none, Vary: Accept-Language,Accept-Encoding, Transfer-Encoding: chunked] cz.msebera.android.httpclient.conn.BasicManagedEntity#2bffe96
D/HwRTBlurUtils: check blur style for HwToast-Toast, themeResId : 0x7f0d0005, context : com.example.rarestaciu.bikemessengerapp.SecondScreen#309bb49, Nhwext : 6, get Blur : disable with , android.graphics.drawable.NinePatchDrawable#aadbe04
I have to use CURL request to parse an API link using android application.In the response i get an id and username as output.But,I have to display a token value from that API.That token is displayed on Linux machine while running curl.I didn't get the token value in windows machine.I used the code like this:
HttpClient httpclient = new DefaultHttpClient();
HttpPost httppost = new HttpPost("http://moneyplayer.herokuapp.com/users.json");
JSONObject json_one,json;
json_one = new JSONObject();
json =new JSONObject();
json.put("password","userPwd");
json.put("username","userEmail");
json_one.put("user",json);
Log.v("JSON Response is",""+json_one);
StringEntity se = new StringEntity(json_one.toString());
se.setContentType(new BasicHeader(HTTP.CONTENT_TYPE, "application/json"));
httppost.setEntity(se);
httppost.setHeader("Content-type","application/json");
// Execute HTTP Post Request
HttpResponse response = httpclient.execute(httppost);
String responseStr = EntityUtils.toString(response.getEntity());
Log.v("Response String Value is",""+responseStr);
In Linux machine the output is displayed like this:
{"id":37,"username":"testing123#1234.com"}
HTTP/1.1 200 O4 Cache-Control:max-age=0, private, must-revalidate
Content-Type:application /json;
charset=utf-8 Date: Mon, 17 Mar 2014 15:33:51 GMT
Etag:"a8979713bed4432cb624cb404df16a53"
Set-Cookie:
remember_token=BAhbCGkqSSIlMTZkYmE4ZDhhZTA2YzI2OWQwZjM2Y2ZjZjNmY2YyZGUGOgZFRjA%3D--d29db574adf7a4df8671eb75f43166101b81ef65; path=/; expires=Fri, 17-Mar-2034 15:33:51 GMT
Set-Cookie:
_live_local_web_session=BAh7B0kiCmZsYXNoBjoGRVRvOiVBY3Rpb25EaXNwYXRjaDo6Rmxhc2g6OkZsYXNoSGFzaAk6CkB1c2VkbzoIU2V0BjoKQGhhc2h7BjoOc3VjY2Vzc2VzVDoMQGNsb3NlZEY6DUBmbGFzaGVzewY7ClsGSSIiU3VjY2Vzc2Z1bGx5IGNyZWF0ZWQgcHJvZmlsZS4GOwBUOglAbm93bzokQWN0aW9uRGlzcGF0Y2g6OkZsYXNoOj
I try to send POST request to some server with json parameters and I wait json response.
From Android it works fine but from Linux I get status 302 redirect. I really don't know where is my problem.
Here is command from linux:
curl -i -X POST --data "id=105&json={\"orderBy\":0\"maxResults\":50}" "http://mysite.com/ctlClient/"
And I get response:
HTTP/1.1 302 Found
Date: Thu, 04 Jul 2013 12:22:06 GMT
Server: Apache
X-Powered-By: PHP/5.3.19
Set-Cookie: PHPSESSID=dqblvijvttgsdrv2u5tn72p9d6; path=/
Expires: Thu, 19 Nov 1981 08:52:00 GMT
Cache-Control: no-store, no-cache, must-revalidate, post-check=0, pre-check=0
Pragma: no-cache
location: http://mysite.com/fwf/online/
Content-Length: 0
Connection: close
Content-Type: text/html
From Server access log:
"POST /ctlClient/ HTTP/1.1" 302 - "-" "curl/7.15.5 (x86_64-redhat-linux-gnu) libcurl/7.15.5 OpenSSL/0.9.8b zlib/1.2.3 libidn/0.6.5"
Android:
String data = "{\"orderBy\":0\"maxResults\":50}";
String WEFI_MAIL_URL = "http://mysite.com/ctlClient/";
DefaultHttpClient httpclient = null;
String out = null;
try {
httpclient = new DefaultHttpClient();
HttpPost httpost = new HttpPost(WEFI_MAIL_URL);
httpost.setHeader("User-Agent", "Apache-HttpClient/4.1 (java 1.5)");
List <NameValuePair> nvps = new ArrayList <NameValuePair>();
nvps.add(new BasicNameValuePair("id", "105"));
nvps.add(new BasicNameValuePair("json", data));
httpost.setEntity(new UrlEncodedFormEntity(nvps, HTTP.UTF_8));
HttpResponse response = httpclient.execute(httpost);
HttpEntity entity = response.getEntity();
if (entity != null) {
InputStream is = entity.getContent();
InputStreamReader isr = new InputStreamReader(is);
BufferedReader br = new BufferedReader(isr);
String line = null;
while ( (line = br.readLine()) != null) {
out = line;
}
is.close();
if(isTimeOut == false){
_loadActual();
}
else{
return;
}
} else {
return;
}
} catch (Exception e) {
}
if (httpclient != null) {
httpclient.getConnectionManager().shutdown();
}
}
access log on Android response:
"POST /ctlClient/ HTTP/1.1" 302 - "-" "Apache-HttpClient/4.1 (java 1.5)"
"GET /fwf/online/ HTTP/1.1" 200 13981 "-" "Apache-HttpClient/4.1 (java 1.5)"
We can see that on POST server redirects me to /fwf/online/
From Wireshark i get the same results from both methods:
POST /ctlClient/ HTTP/1.1
User-Agent: Apache-HttpClient/4.1 (java 1.5)
Content-Type: application/x-www-form-urlencoded
Content-Length: 301
Host: mysite.com
Connection: Keep-Alive
Why it works from Android but not from Linux with CURL?
Can anybody help me or give me direction how can i solve it?
Thank you
You want to add -L to your curl command. See http://curl.haxx.se/docs/faq.html#How_do_I_tell_curl_to_follow_HTT.
I have faced with one problem - returning 401 error msg when you already signed in and trying to get access to another secured pages. The mystic of this problem for me is that I can get access to another secured pages after you are signed in if check it via Firefox RestCLient or via iOS app but cannot get access via Chrome Advanced Rest Client and Android app. However, content-type and other necessary params are set the same in both web tools and apps. I have tried to set different auth headers with encoded login:pass but it doesnt help and it doesnt need because it should work without it, I think(at least FF and iOS app work without this header). What`s gonna be wrong?
Response headers of Chrome:
401 Unauthorized
Loading time:
29
Request headers
Content-Type: application/x-www-form-urlencoded
Response headers
Date: Mon, 04 Mar 2013 10:01:02 GMT
Server: Apache/2.2.20 (Ubuntu)
X-Powered-By: PHP/5.3.6-13ubuntu3.9
Set-Cookie: peachy=qg3mjvchjh1oionqlhhv0jrn71; path=/
Expires: Thu, 19 Nov 1981 08:52:00 GMT
Cache-Control: no-store, no-cache, must-revalidate, post-check=0, pre-check=0
Pragma: no-cache
Vary: Accept-Encoding
Content-Length: 96
Keep-Alive: timeout=5, max=100
Connection: Keep-Alive
Content-Type: text/html; charset=utf-8
Response headers of Firefox:
Status Code: 200 OK
Cache-Control: no-store, no-cache, must-revalidate, post-check=0, pre-check=0
Connection: Keep-Alive
Content-Length: 202
Content-Type: application/json
Date: Mon, 04 Mar 2013 09:51:09 GMT
Expires: Thu, 19 Nov 1981 08:52:00 GMT
Keep-Alive: timeout=5, max=100
Pragma: no-cache
Server: Apache/2.2.20 (Ubuntu)
X-Powered-By: PHP/5.3.6-13ubuntu3.9
That is my peace of Restful code in Android app:
public String serverRequest(int action, Bundle params) {
if (action == 0) {
if (Const.DEBUG_ENABLED)
Log.e(TAG, "You did not pass action.");
return "You did not pass action.";
}
try {
HttpRequestBase request = null;
HttpPost postRequest = null;
switch (action) {
case SIGN_IN:
request = new HttpPost();
request.setURI(new URI(SIGNIN_URL));
request.setHeader("Content-Type", "application/x-www-form-urlencoded; charset=utf-8");
postRequest = (HttpPost) request;
if (params != null) {
UrlEncodedFormEntity formEntity = new
UrlEncodedFormEntity(paramsToList(params));
postRequest.setEntity(formEntity);
}
break;
case SIGN_OUT:
request = new HttpPost();
request.setURI(new URI(SIGNOUT_URL));
request.setHeader("Content-Type", "application/x-www-form-urlencoded; charset=utf-8");
break;
case BANK_CARD_VERIFY:
request = new HttpPost();
request.setURI(new URI(BANK_CARD_VERIFY_URL));
request.setHeader("Content-Type", "application/x-www-form-urlencoded; charset=utf-8");
postRequest = (HttpPost) request;
if (params != null) {
UrlEncodedFormEntity formEntity = new UrlEncodedFormEntity(paramsToList(params));
postRequest.setEntity(formEntity);
}
break;
}
if (request != null) {
DefaultHttpClient client = new DefaultHttpClient();
if (Const.DEBUG_ENABLED)
Log.d(TAG, "Executing request: " + actionToString(action) + ": " + urlToString(action));
HttpResponse response = client.execute(request);
StatusLine responseStatus = response.getStatusLine();
int statusCode = responseStatus != null ? responseStatus.getStatusCode() : 0;
Log.d(TAG, "Status code: " + statusCode);
}
}
(sign in and sign out are public, bank_verify is secured page. Android app has the same response headers like chrome). It seems there is something problem with session or something else but I`m not sure exactly.
EDIT:
It seems I have found what`s the problem here. In Android app I create a new HttpCLient object due to it all old data is losed. But another question - how to make this HttpCLient reusable?
Problem found. I reuse httpClient everytime in spite of that to use only one which has all session data everytime. Just implement if statement to check if I have already httpclient object then you it otherwise create a new.