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.
Related
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 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
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 can get a cookie with firefox, but not with android.
This is the code:
HttpParams httpparams = new BasicHttpParams();
httpparams.setParameter(ClientPNames.COOKIE_POLICY,CookiePolicy.BROWSER_COMPATIBILITY);
HttpGet httpget = new HttpGet(sURL);
httpget.setParams(httpparams);
httpget.setHeader("User-Agent","Mozilla/5.0 (X11; U; Linux i686; en-US; rv:1.9.2.2) Gecko/20100316 Firefox/3.6.2");
httpget.setHeader("Accept", "text/html,application/xhtml+xml,application/xml;q=0.9,*/*;q=0.8");
httpget.setHeader("Accept-Language", "es-mx,es;q=0.8,en-us;q=0.5,en;q=0.3");
httpget.setHeader("Accept-Encoding", "gzip,deflate");
httpget.setHeader("Accept-Charset", "ISO-8859-1,utf-8;q=0.7,*;q=0.7");
httpget.setHeader("Keep-Alive", "115");
BasicHttpResponse response = (BasicHttpResponse) httpclient.execute(httpget);
Using wireshrack I saw:
GET /login.php HTTP/1.1
User-Agent: Mozilla/5.0 (X11; U; Linux i686; en-US; rv:1.9.2.2) Gecko/20100316 Firefox/3.6.2
Accept: text/html,application/xhtml+xml,application/xml;q=0.9,*/*;q=0.8
Accept-Language: es-mx,es;q=0.8,en-us;q=0.5,en;q=0.3
Accept-Encoding: gzip,deflate
Accept-Charset: ISO-8859-1,utf-8;q=0.7,*;q=0.7
Keep-Alive: 115
Host: www.conquerclub.com
Connection: Keep-Alive
and the response is using my code:
HTTP/1.1 200 OK
Date: Mon, 09 Aug 2010 05:41:38 GMT
Server: Apache/2.0.52 (Red Hat)
X-Powered-By: PHP/5.2.13
Set-Cookie: referer=%5Bdirect%5D; path=/
Set-Cookie: referer60=%5Bdirect%5D; expires=Wed, 08-Sep-2010 05:41:38 GMT; path=/
Connection: close
Transfer-Encoding: chunked
Content-Type: text/html
but whith Firefox the response is
HTTP/1.1 200 OK
Date: Mon, 09 Aug 2010 05:11:13 GMT
Server: Apache/2.0.52 (Red Hat)
X-Powered-By: PHP/5.2.13
Set-Cookie: referer=%5Bdirect%5D; path=/
Set-Cookie: referer60=%5Bdirect%5D; expires=Wed, 08-Sep-2010 05:11:13 GMT; path=/
Set-Cookie: PHPSESSID=sv8f6ro571t9rv999mu6jtkbu3; path=/; HttpOnly
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
Content-Encoding: gzip
Vary: Accept-Encoding
Content-Length: 4324
Connection: close
Content-Type: text/html
again using wireshark to see firefox I got this:
GET / HTTP/1.1
Host: www.conquerclub.com
User-Agent: Mozilla/5.0 (X11; U; Linux i686; en-US; rv:1.9.2.2) Gecko/20100316 Firefox/3.6.2
Accept: text/html,application/xhtml+xml,application/xml;q=0.9,*/*;q=0.8
Accept-Language: es-mx,es;q=0.8,en-us;q=0.5,en;q=0.3
Accept-Encoding: gzip,deflate
Accept-Charset: ISO-8859-1,utf-8;q=0.7,*;q=0.7
Keep-Alive: 115
Connection: keep-alive
It is the same, but the server don't respond this line
Set-Cookie: PHPSESSID=sv8f6ro571t9rv999mu6jtkbu3; path=/; HttpOnly
why? any idea would be very well receive.
I came across a similar problem with android. This happens because of the cookie origin policy in Browser compatibility mode. The HTTP client in android is rejecting the cookie because the cookie's path does not match the current requested document's path.
e.g. if your cookie path is: /mypath, and your cookie is originating from: /mypath/myAdditionalPath, the http client will reject the cookie (internally throwing a MalformedCookieException). But browsers will accept such cookies.
To workaround this problem in your code, you will have to implement your own cookie spec the one that extends from BrowserCompatSpec. Here's some sample skeleton code:
public class MyCookieSpec extends BrowserCompatSpec {
#Override
public void validate(Cookie cookie, CookieOrigin origin) throws
MalformedCookieException {
if(cookie == null) {
throw new IllegalArgumentException("Cookie cannot be null");
}
if(origin == null) {
throw new IllegalArgumentException("Cookie origin cannot be null");
}
// use these logs to see what is the difference between paths of the
// cookieOrigin and the cookie.
String pth = cookie.getPath();
Log.i(TAG, "Cookie ====================================> " + cookie);
Log.i(TAG, "CookieOrigin ====================================> " + origin);
// Check if the cookie is from the same domain, if so return silently
// or else throw a MalformedCookieException
}
#Override
public boolean match(Cookie cookie, CookieOrigin origin) {
if(cookie == null) {
throw new IllegalArgumentException("Cookie cannot be null");
}
if(origin == null) {
throw new IllegalArgumentException("Cookie origin cannot be null");
}
if(Log.isLoggable(TAG, Log.DEBUG)) {
Log.d(TAG, "Matching cookie " + cookie + " with origin " + origin);
}
// if the cookie is originating from the same domain as of the origin
// return true or return false. Be careful here and only return true if
// the cookie is originating from the same domain as that of what is in the
// cookie's path
return true;
}
}
To register and use this cookie spec with your http client, use the following:
DefaultHttpClient httpClient = new DefaultHttpClient(cm, params);
httpClient.getCookieSpecs().register("myspec", new CookieSpecFactory() {
public CookieSpec newInstance(HttpParams hp) {
return new MyCookieSpec();
}
});
httpClient.getParams().setParameter(ClientPNames.COOKIE_POLICY, "myspec");
Sorry guys. I realized that i made a mistake
With firefox, I request www.conquerclub.com with path "/"
BUT using my code I request www.conquerclub.com with path "/login.php"
After I deleted it "login.php", the request return 3 cookies