how to get the information from a http head in android - android

i've been given the task to send a POST message to the server giving it a JSON encoded message. The server would then send back a responce in a custom HTTP header field “X-SubmissionResponse”
so far i can successfully connect to the server (i know this because i get the responce code 202)
but i am having a lot of difficulty in getting the information from the responce, below is the code that i am currently using.
Error content not available
This code ends up returning null, Can anyone see what i am missing here?
This is the code above the if statement ^
Error content not available

Header name = response.getFirstHeader("X-SubmissionResponse");
String whatsInhere = "";
if (name != null)
whatsInhere = name.getValue();
Try using the correct methods of the Class Header.
See http://hc.apache.org/httpcomponents-core-ga/httpcore/apidocs/org/apache/http/Header.html

HttpHead head = new HttpHead();
creates a new HEAD request, empty, that does not do anything in itself.
You want the header from the response to your request. Get it by simply:
Header name = response.getFirstHeader("X-SubmissionResponse");

Related

Getting Server Error when Posting empty String in Volley

In the post request I am posting some parameter to the server as a request body . But unable to post empty string . So the question is that can we make post request with empty string if yes then how?
My code snippet is ..
HashMap<String, String> paramList = new HashMap<>();
paramList.put("ApplicationCode", Constant.Application_Code);
paramList.put("LoginType", Constant.getLoginType(spnLoginType.getSelectedItem().toString()));
paramList.put("BrandCode", Constant.BRAND);
paramList.put("CountryCode", Constant.CountryCode);
paramList.put("CompanyId", etCompanyId.getText().toString().toUpperCase());
paramList.put("UserId", etUserId.getText().toString().toUpperCase());
paramList.put("AppVersion", Constant.API_VERSION_VALUE);
paramList.put("IpAddress", "");
paramList.put("IpAddress", ""); here I am posting empty String that
does not work
And if I post like this paramList.put("IpAddress", "null"); worked
fine.
In the server-side validation, information is being sent to the server
and validated using one of server-side languages. If the validation
fails, the response is then sent back to the client .
But when send as a String does not worked
Why ?
Sloppy mistake coming from server side. Rectify your Server-side Validation .

Retrofit 500 internal server error

I have a post registration webserivce as the following
#FormUrlEncoded
#POST("register/default")
Observable<BaseResponse> doRegistration(#Field("name") String name,#Field(value = "email",encoded = true) String email,#Field("phone_number") String phone_number,#Field("password") String password,#Field("password_confirmation") String password_confirmation);
I've tried with postman to consume this service , and it replies with the response of registration , from android side it causes an exception (500 internal server error ) ,
when and only using a symbol # on the email field , also i've tried the encode option flag mentioned above, UTF-8 encoding but it doesn't interpreted as an email by server side.
is there is a retrofit related issue !
It was a server related issue on creating new record so larvae returns the default exception response with internal server error.

Android Webview POST request

I'm trying to do a post request with a WebView on Android.
After searching for days and trying dozens of things i couldn't get it work. In SWIFT it's just a few lines of code so i thought there must also be a simple way to do a post request for a webview on android.
As (for 2016) EncodingUtils and HTTPClient are deprecated this are my current approaches:
String url = "http://example.com/php.php";
String postData = null;
postData = "param1=" + URLEncoder.encode("1234567890", "UTF-8");
webcontent.postUrl(url,postData.getBytes());
//or
webcontent.postUrl(url, Base64.encode(postData.getBytes(), Base64.DEFAULT));
Both just result in a blank screen. There is just one parameter to be sent and a string containing html from the server should be received.
In addition, the php on the server returns a html-string with colored background irrespective of any input, but even this isn't displayed so maybe the whole request never reaches the server?
Thanks in advance!
In Android you do not use webView to access the content of the HTTP response. You'll need to use HttpClient for that purpose!
See this nice tutorial which explains the fundamentals! Also see this video if you find it hard!
Hope it helps!

Missing parameter access_token on OAuth2 request

I'm using the Apache Amber libraries to try to retrieve an OAuth2 access token from a Web site under my control. My client code is running under Android.
My code is patterned on the example at:
https://cwiki.apache.org/confluence/display/AMBER/OAuth+2.0+Client+Quickstart
In the first step, I'm able to retrieve a "code" by submitting a GET request using a WebView browser:
OAuthClientRequest request = OAuthClientRequest
.authorizationLocation(AUTHORIZE_URL)
.setClientId(CLIENT_ID)
.setRedirectURI(REDIR_URL)
.setResponseType(CODE_RESPONSE)
.buildQueryMessage();
webview.loadUrl(request.getLocationUri());
I use a WebViewClient callback to capture the redirect URL with the "code" parameter. So far, so good.
Using that code, I try to retrieve my access token:
OAuthClient oAuthClient = new OAuthClient(new URLConnectionClient());
OAuthClientRequest request = OAuthClientRequest
.tokenLocation(ACCESS_TOKEN_URL)
.setGrantType(GrantType.AUTHORIZATION_CODE)
.setClientId(CLIENT_ID)
.setClientSecret(CLIENT_SECRET)
.setRedirectURI(REDIR_URL)
.setCode(code)
.buildBodyMessage();
GitHubTokenResponse oAuthResponse =
oAuthClient.accessToken(request, GitHubTokenResponse.class);
Each time I run my code, I get an OAuthProblemException, where the message is that I have an invalid request due to a missing parameter, access_token.
Another StackOverflow post mentions this exception from a similar OAuth2 request, which in that case was caused by having different redirect URIs across OAuth requests. But I've made sure my redirect URIs are the same by using a named constant. Here's the link to that post:
OAuthProblem, missing parameter access_token
Now, I can print out the code returned by the first request, and paste it into a curl command run from my desktop machine:
curl -d "code=...&client_id=...&client_secret=...&grant_type=...&redirect_uri=..." http://my_website.com
and I get a nice JSON response from my site with an access_token.
Why does the call from Java fail, where my hand-rolled command line succeeds?
I had the same problem implementing the client and the server, the problem is about one mistake in the Client Example in the Apache Amber (Oltu) project:
First you have the Auth code request (which work):
OAuthClientRequest request = OAuthClientRequest
.authorizationLocation(AUTHORIZE_URL)
.setClientId(CLIENT_ID)
.setRedirectURI(REDIR_URL)
.setResponseType(CODE_RESPONSE)
.**buildQueryMessage**();
And second the request about the Access Token (which don't work):
OAuthClientRequest request = OAuthClientRequest
.tokenLocation(ACCESS_TOKEN_URL)
.setGrantType(GrantType.AUTHORIZATION_CODE)
.setClientId(CLIENT_ID)
.setClientSecret(CLIENT_SECRET)
.setRedirectURI(REDIR_URL)
.setCode(code)
.**buildBodyMessage**();
The mistake is about the buildBodyMessage() in the second request. Change it by buildQueryMessage().
Solved in my case.
Amber/Oltu "Missing parameter access_token" error may mean that GitHubTokenResponse or OAuthJSONAccessTokenResponse are unabled to translate response body for any reason. In my case (with Google+ oAuth2 authentication), the response body, is not parsed properly to the inner parameters map.
For example:
GitHubTokenResponse
parameters = OAuthUtils.decodeForm(body);
Parse a form-urlencoded result body
... and OAuthJSONAccessTokenResponse has the next parse function
parameters = JSONUtils.parseJSON(body);
This JSONUtils.parseJSON is a custom JSON parser that not allow for me JSON response body from GOOGLE+ and throws an JSONError (console not logged),
Each error throwed parsing this parameters, are not console visible, and then always is throwed doomed "Missing parameter: access_token" or another "missing parameter" error.
If you write your Custom OAuthAccessTokenResponse, you can see response body, and write a parser that works with your response.
This is what I encountered and what I did to get it working:
I quickly put together a similar example described in:
https://cwiki.apache.org/confluence/display/OLTU/OAuth+2.0+Client+Quickstart
and:
svn.apache.org/repos/asf/oltu/trunk/oauth-2.0/client/src/test/java/org/apache/oltu/oauth2/client/OAuthClientTest.java
This was my command to execute it:
java -cp .:./org.apache.oltu.oauth2.client-1.0.1-20150221.171248-36.jar OAuthClientTest
I also ended up with the above mentioned error where the access_token was expected. I ended up debugging in intellij and traced an anomaly with the if condition which checks that the string begins with the "{" character.
In doing so, I also added the following jar to my classpath so that I may debug the trace a little deeper.
./java-json.jar
(downloaded from http://www.java2s.com/Code/Jar/j/Downloadjavajsonjar.htm)
During the next debug session, the code actually started working. My mate and I eventually found the root cause was due to the JSON jar not being included.
This is the command which works:
java -cp .:./java-json.jar:./org.apache.oltu.oauth2.client-1.0.1-20150221.171248-36.jar OAuthClientTest
I was having the same problem when trying to get the access token from fitbit OAuth2. buildBodyMessage() and buildQueryMessage() were both giving me missing parameter, access_token.
I believe this is something to do with the apache oauth2 client library. I ended up making simple post requests using spring's RestTemplate and it's working fine.
HttpHeaders headers = new HttpHeaders();
headers.setContentType(MediaType.APPLICATION_FORM_URLENCODED);
headers.set("Authorization", "Basic " + "MjI5TkRZOjAwNDBhNDBkMjRmZTA0OTJhNTE5NzU5NmQ1N2ZmZGEw");
MultiValueMap<String, String> map = new LinkedMultiValueMap<>();
map.add("client_id", FITBIT_CLIENT_ID);
map.add("grant_type", "authorization_code");
map.add("redirect_uri", Constants.RESTFUL_PATH + "/fitbit/fitbitredirect");
map.add("code", code);
HttpEntity<MultiValueMap<String, String>> request = new HttpEntity<>(map, headers);
RestTemplate restTemplate = new RestTemplate();
ResponseEntity<String> response = restTemplate.postForEntity(FITBIT_TOKEN_URI, request, String.class);
log.debug("response.body: " + response.getBody());

How to get Hyperlink from whole string

I create an application in which i get the response from web service .
The response is
"I might be in danger. I have triggered my panic alarm which is connected to you. Call me now. If i'm not answering, contact the police. My position is:http://maps.google.com/maps?q=21.183783,72.823548"
3.I store the string in text view.and i want to open HTTP URL in browser,on the click of text.but how can i get HTTP URL in whole string plese give me idea.
You can do this easily with php...
If you are able to run php, this should do it.
$string = $_GET['string'];
OR
$string = $_POST['string'];
this may change depending on how you get the responce from the website, feel free to send me the form which you get the responce and ill change it accordingly.
$string_chunks = explode('http://',$string,2);
$url = 'http://'.$string_chunk['1'];
Basically, this will take the string, find the "http://" and create 2 strings out of it. one with the content before the "http://" and one with the content after, which is the url. so it would return $string_chunk['0'] and $string_chunk['1']
var response = "ur response string";
var indexofHttp = response.indexOf('http://');
var url = response.substring(indexofHttp);

Categories

Resources