private void login() {
androidID = Secure.getString(MainActivity.this.getContentResolver(), Secure.ANDROID_ID);
String uP = androidID.concat(":ClientTrustedSecret");
byte[] authByteAry = null;
try {
authByteAry = uP.getBytes("UTF-8");
} catch (UnsupportedEncodingException e1) {
e1.printStackTrace();
}
String base64 = Base64.encodeToString(authByteAry, Base64.DEFAULT).trim();
client.addHeader("Authorization", "Basic ".concat(base64));
// Following format is required to post to OAuth
JSONObject jsonObject = new JSONObject();
try {
jsonObject.put("grant_type", "password");
jsonObject.put("username", "abc");
jsonObject.put("password", "abc");
} catch (JSONException e1) {
e1.printStackTrace();
}
String contentType = "application/json; charset=UTF-8";
StringEntity data = null;
try {
// Send the json to the server
data = new StringEntity(jsonObject.toString());
client.post(MainActivity.this, baseURL.concat("/tokens"), data, contentType, new AsyncHttpResponseHandler() {
#Override
public void onSuccess(String response) {
try {
JSONObject jsonObject = new JSONObject(response);
oauthAccessTokenString = jsonObject.get("access_token").toString();
} catch (JSONException e) {
e.printStackTrace();
}
}
#Override
public void onFailure(Throwable t, String err) {
System.out.println("login failed");
}
});
} catch (UnsupportedEncodingException e) {
e.printStackTrace();
}
}
The above is how I login. And when making another web serivce call I get the unauthorized. The unlock method requires the following headers.
http://i.imgur.com/EaWDO.png
private void unlock()
{
AsyncHttpClient asyncHttpClient = new AsyncHttpClient();
asyncHttpClient.addHeader("Locale", "en_US");
asyncHttpClient.addHeader("X-Originator-Type", "app");
asyncHttpClient.addHeader("Content-Type", "application/json");
// asyncHttpClient.addHeader("Connection", "Keep-Alive");
// asyncHttpClient.addHeader("X-Device-Id", androidID);
// asyncHttpClient.addHeader("X-via", deviceId);
// asyncHttpClient.addHeader("ClientID", "abc#abc.com");
asyncHttpClient.addHeader("Authorization", "Bearer ".concat(oauthAccessTokenString));
asyncHttpClient.get("host/users?loginName=abc#abc.com", new AsyncHttpResponseHandler() {
#Override
public void onSuccess(String response) {
System.out.println(response);
}
#Override
public void onFailure(Throwable t, String err) {
System.out.println("Unlock server call failed");
Log.d("printing error: ", err);
}
});
}
Above code throws 401 unauthorized exception. No references in documentation which I have, to call back url. I am providing the oauth access token just fine, but then why is it that I still get 401? Does the secret has anything to do with the second call? I am told is that I need to set up my headers that way. I am also told that "For https, the client needs to be able to handle the validation of the certificate. Does anyone knows how to solve it?
It was a wrong web service address :( There was no need to handle the validation of the certificate. There was nothing about call back url. The secret had nothing to do. But the documentation that I have is very poorly written, at one place they mentioned only the headers and then in another place they say body is required is well. So just make sure you go through the documents properly.
Related
I'm using an asynchronous request (because synchronous doesn't work correctly with this API), the OkHttp3 library. Inside the request, I get a response in the form of JSON. I need to somehow pass values from Json to a class variable. I decided to try it this way, but it doesn't work.
public String sessionId = null;
...
public QRcodeReader() throws Exception {
this.sessionId = null;
}
... // between this code I have 1 function, which reg my number.
// in this func I need to confirm my phone by code in SMS.
public void SmsCode(String Code) // String get from another class
{
SmsJson smsJson = new SmsJson("*phoneNumber*", "*secret_key*", "*os*", Code);
Gson gson = new GsonBuilder().disableHtmlEscaping().create();
RequestBody body = RequestBody.create(
MediaType.parse("application/json"), gson.toJson(smsJson));
Request request = new Request.Builder()
.url("https://irkkt-mobile.nalog.ru:8888/v2/auth/phone/verify")
.addHeader("Host", HOST)
.addHeader("Accept", ACCEPT)
.addHeader("Device-OS", DEVICE_OS)
.addHeader("Device-ID", DEVICE_ID)
.addHeader("clientVersion", CLIENT_VERSION)
.addHeader("Accept-Language", ACCEPT_LANGUAGE)
.addHeader("User-Agent", USER_AGENT)
.post(body)
.build();
httpClient.newCall(request).enqueue(new Callback() {
#Override
public void onResponse(#NonNull Call call, #NonNull Response response) throws IOException {
try (Response responseBody = httpClient.newCall(request).execute()) {
if (!responseBody.isSuccessful())
throw new IOException("Unexpected code " + responseBody);
// Here I try to transfer data from request to class variable. Not Work.
SetSessionId(Objects.requireNonNull(responseBody.body()).string());
System.out.println(Objects.requireNonNull(responseBody.body()).string());
} catch (IOException e) {
e.printStackTrace();
}
}
#Override
public void onFailure(Call call, IOException e) {
e.printStackTrace();
}
});
}
void SetSessionId(String sessionId){
this.sessionId = sessionId;
}
I need to use SessionID further along here:
public String GetTicketID(String QR){
TicketID ticketID = new TicketID(QR);
Gson gson = new GsonBuilder().disableHtmlEscaping().create();
RequestBody body = RequestBody.create(
MediaType.parse("application/json"), gson.toJson(ticketID));
Request request = new Request.Builder()
.url("https://irkkt-mobile.nalog.ru:8888/v2/ticket")
.addHeader("Host", HOST)
.addHeader("Accept", ACCEPT)
.addHeader("Device-OS", DEVICE_OS)
.addHeader("Device-ID", DEVICE_ID)
.addHeader("clientVersion", CLIENT_VERSION)
.addHeader("Accept-Language", ACCEPT_LANGUAGE)
.addHeader("User-Agent", USER_AGENT)
.addHeader("sessionId", sessionId) // Here I get NULL and exception!
.post(body)
.build();
httpClient.newCall(request).enqueue(new Callback() {
#Override
public void onResponse(Call call, Response response) throws IOException {
try (Response responseBody = httpClient.newCall(request).execute()) {
if (!responseBody.isSuccessful())
throw new IOException("Unexpected code " + responseBody);
System.out.println(Objects.requireNonNull(responseBody.body()).string());
} catch (IOException e) {
e.printStackTrace();
}
}
#Override
public void onFailure(Call call, IOException e) {
e.printStackTrace();
}
});
return ""; // Here I need to transfer id to another variable, not did it yet.
}
The problem is that SessionID = Null and the request does not work.
I think I'm doing something wrong, but I can't figure out what. May be it is because async request..
I had an easy question, I am writing api in laravel and I will put it in my android application, but although the register part and logout part work correctly, when I check from postman in the login section, it takes the token and logs in, but when we come to the application, I get a 401 error when logging in, I wonder why? My login code is in the controller like this:
$credentials = $request->validate([
‘email’=>‘required|email’,
‘password’=>‘required’
]);
if(Auth::attempt($credentials)){
$user=Auth::user();
$token=md5(time()).‘.’.md5($request->email);
$user->forceFill([
‘api_token’=>$token,
])->save();
return response()->json([
‘token’=>$token
]);
}
return response()->json(['message'=>'The provided credentials do not match our records'],401);
}
It gives correct in Postman, it doesn't cause any problem, but I register in the application. It's not a problem. It gives 401 at login, I wonder why? My code in the application is as follows:
private void sendLogin() {
JSONObject params= new JSONObject();
try {
params.put(“email”,email);
params.put(“password”,password);
}catch (JSONException e){
e.printStackTrace();
}
String data = params.toString();
String url = getString(R.string.api_server)+"/login";
new Thread(new Runnable() {
#Override
public void run() {
Http http = new Http(LoginActivity.this,url);
http.setMethod("POST");
http.setData(data);
http.send();
runOnUiThread(new Runnable() {
#Override
public void run() {
Integer code = http.getStatusCode();
if(code == 200){
try{
JSONObject response = new JSONObject(http.getResponse());
String token = response.getString("token");
localStorage.setToken(token);
Intent i = new Intent(LoginActivity.this,UserActivity.class);
startActivity(i);
finish();
}catch (JSONException e){
e.printStackTrace();
}
}
else if(code ==422){
try{
JSONObject response = new JSONObject(http.getResponse());
String msg = response.getString("message");
alertFail(msg);
}catch (JSONException e){
e.printStackTrace();
}
}
else if(code == 401){
try{
JSONObject response = new JSONObject(http.getResponse());
String msg = response.getString("message");
alertFail(msg);
}catch (JSONException e){
e.printStackTrace();
}
}
else{
Toast.makeText(LoginActivity.this,"Error"+code,Toast.LENGTH_SHORT).show();
}
}
});
}
}).start();
}
I'll be happy if you can help me
send this with headers
["Accept"] = "application/json";
["Content-Type"] = "application/json";
["withCredentials"] = true;
and in env laravel add this (values are just for example)
SESSION_DOMAIN=.localhost
SANCTUM_STATEFUL_DOMAINS=localhost,127.0.0.1
Volley response is not showing the Arabic character ف
Instead of this character I'm getting a diamond question mark � .
All the other characters are showing properly, I don't know the what is happening with this character alone.Is it the problem of volley web service?
Any help appreciated.
final RequestQueue requestQueue = Volley.newRequestQueue(Register.this);
String url = Config.url + "validateID";
StringRequest stringRequest = new StringRequest(Request.Method.POST, url, new Response.Listener<String>() {
#Override
public void onResponse(String response) {
response = response.trim();
if (response != null) {
try {
response = new String(response.getBytes(), "UTF-8");
response = Html.fromHtml(response).toString();
response = fixEncodingUnicode(response);
System.out.println("######utf####" + response);
try {
JSONObject jsonObject = new JSONObject(response);
String respCode = jsonObject.getString("responseCode");
String status = jsonObject.getString("status");
if (respCode.equals("200") && status.equals("ACTIVE")) {
ed_full_name.setText(jsonObject.getString("name"));
ed_full_name_arabic.setText(jsonObject.getString("namearabic"));
}
} catch (JSONException e) {
e.printStackTrace();
}
} catch (UnsupportedEncodingException e) {
e.printStackTrace();
}
}
}
}, new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
progressDialog.dismiss();
}
public static String fixEncodingUnicode(String response) {
String str = "";
try {
str = new String(response.getBytes("windows-1254"), "UTF-8");
} catch (UnsupportedEncodingException e) {
e.printStackTrace();
}
String decodedStr = Html.fromHtml(str).toString();
return decodedStr;
}
I am afraid the patching code from a wrong encoding to a correct encoding cannot guarantee all characters survive the process. The main principle in java is that String always holds Unicode text; so there always is a conversion to bytes representing text in some encoding.
response = new String(response.getBytes(), "UTF-8");
This is wrong. getBytes() without charset uses the default charset from the platform which runs the current application. So it has a different effect on your development Windows PC and the production Linux server. Any effect is totally misleading.
response = Html.fromHtml(response).toString();
This encodes HTML entities. In a request a sign then the <form> is missing an accept-encoding="UTF-8". Part of the request headers. Then the browser sends non-Latin as HTML entities.
Here it might be a communication failure between layers, where the request part is missing a UTF-8 accepting header.
response = fixEncodingUnicode(response); or str = new String(response.getBytes("windows-1254"), "UTF-8");
Unneeded as String in java already is in Unicode. It would introduce a diamond whenever a Unicode symbol was not translatable in Windows-1254.
So all seems wrong. The error seems to be made earlier on.
Correct the requests, as otherwise a correct request might give wrong results. Go for UTF-8 rather than Windows-1254.
You can dump, log the bytes if the input parameter response, with something like:
Arrays.toString(response.codePoints().toArray())
(A hexadecimal format would be more readable.)
As #Joop Eggen said, no need of html and Windows-1254 encoding. Just use the default enocding of Volley that is ISO-8859-1.
response = new String(response.getBytes("ISO-8859-1"), "UTF-8");
complete code is below.
final RequestQueue requestQueue = Volley.newRequestQueue(Register.this);
String url = Config.url + "validateID";
StringRequest stringRequest = new StringRequest(Request.Method.POST, url, new Response.Listener<String>() {
#Override
public void onResponse(String response) {
response = response.trim();
if (response != null) {
try {
response = new String(response.getBytes("ISO-8859-1"), "UTF-8");
try {
JSONObject jsonObject = new JSONObject(response);
String respCode = jsonObject.getString("responseCode");
String status = jsonObject.getString("status");
if (respCode.equals("200") && status.equals("ACTIVE")) {
ed_full_name.setText(jsonObject.getString("name"));
ed_full_name_arabic.setText(jsonObject.getString("namearabic"));
}
} catch (JSONException e) {
e.printStackTrace();
}
} catch (UnsupportedEncodingException e) {
e.printStackTrace();
}
}
}
}, new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
progressDialog.dismiss();
}
how to make post call asynchronously (jersy)? I do not want to get any response from this url
public void callAPI(String url,int Id,long se_eln,String reportName String ,String startDate, String endDate){
Map map= new HashMap();
map.put("Id", Id);
map.put("reportName",reportNameString);
map.put("startDate", startDate);
map.put("endDate", endDate);
map.put("accountId", se_eln);
try {
//System.out.println("calling post method");
String str = new ObjectMapper().writeValueAsString(dataMismatchMap);
//
//PostMethod postMethod = new PostMethod(url);
PostMethod postMethod = new PostMethod(url);
RequestEntity requestEntity = new StringRequestEntity(str);
postMethod.setRequestEntity(requestEntity);
postMethod.setRequestHeader("Content-Type", "application/json;charset=utf-8");
HttpClient httpclient = new HttpClient();
int result = httpclient.executeMethod(postMethod);
//System.out.println("result is "+result);
webre
} catch (MalformedURLException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
}
how to make post call asynchronously (jersy)? I do not want to get any response from this url
i think there is way to make async calls in apache http client, as i can see you already using it. at simplest you can put request call in simple thread and let let it execute. if i find on making async call through http client will update answer...
This is for get but you can modify to use post replace .rx().get(); by rx().post(...); .
rx.Observable<Response> observable = Rx.newClient(RxObservableInvoker.class)
// .target("http://javaresteasydemo-ravikant.rhcloud.com/rest/hello/getDataNoZip/")
.target("http://jerseyexample-ravikant.rhcloud.com/rest/jws/getDataAsClient")
.register(JacksonFeature.class).request().header("key", "12345").rx().get();
observable.subscribe(new Action1<Response>() {
#Override
public void call(Response response) {
try {
System.out.println(" Inside call ");
// System.out.println(response.readEntity(List.class));
//List<java.util.LinkedHashMap> lst = response.readEntity(List.class);
ObjectMapper ob = new ObjectMapper();
List<User> pojos = ob.convertValue(response.readEntity(List.class), new TypeReference<List<User>>() {
});
for (User user : pojos) {
System.out.println(user.getPost());
}
} catch (Exception e) {
e.printStackTrace();
}
System.exit(0);
}
});
Let's say there is a 3rd party RESTful web service exposing a GET endpoint at:
http://someservice.com/api/askAnyQuestion
And I want to hit that service, placing my question on the query string:
http://someservice.com/api/askAnyQuestion&q=Does%20my%20dog%20know%20about%20math%3F
How do I hit this service from a client-side GWT application? I've been reading the RequestFactory tutorials, but RF seems to be only for providing a data access layer (DAL) and for CRUDding entities, and I'm not entirely sure if it's appropriate for this use case.
Extra super bonus points if anyone can provide a code sample, and not just a link to the GWT tutorials, which I have already read, or some Googler's blog, which I have also probably read ;-).
You can use RequestBuilder. Successfully used it to work with REST.
RequestBuilder builder = new RequestBuilder(RequestBuilder.GET, url);
try {
builder.sendRequest(null, new RequestCallback() {
#Override
public void onError(Request request, Throwable exception) {
// process error
}
#Override
public void onResponseReceived(Request request, Response response) {
if (200 == response.getStatusCode()) {
// process success
} else {
// process other HTTP response codes
}
}
});
} catch (RequestException e) {
// process exception
}
Please also take a look at this question for cross site requests related info.
I had the same problem few days ago and tried to implement it with requestBuilder. You will receive a Cross-Domain Scripting issue.
https://developers.google.com/web-toolkit/doc/1.6/FAQ_Server#How_can_I_dynamically_fetch_JSON_feeds_from_other_web_domains?
I did handle this by a RPC Request to my Server, and from there a Server-Side HTTP Request to the Cross-Domain URL.
https://developers.google.com/web-toolkit/doc/latest/tutorial/Xsite
public static void SendRequest(String method, String notifications) {
String url = SERVICE_BASE_URL + method;
JSONObject requestObject = new JSONObject();
JSONArray notificationsArray =null;
JSONObject mainRequest = new JSONObject();
try {
notificationsArray = new JSONArray(notifications);
requestObject.put("notifications", notificationsArray);
mainRequest.put("request", requestObject);
} catch (JSONException e1) {
// TODO Auto-generated catch block
e1.printStackTrace();
}
HttpURLConnection connection = null;
try
{
URL server = new URL(url);
connection = (HttpURLConnection) server.openConnection();
connection.setRequestMethod("POST");
connection.setRequestProperty("Content-Type", "application/json");
connection.setDoInput(true);
connection.setDoOutput(true);
DataOutputStream writer = new DataOutputStream(connection.getOutputStream());
writer.writeBytes(mainRequest.toString());
writer.flush();
writer.close();
parseResponse(connection);
}
catch (Exception e)
{
System.out.println("An error occurred: " + e.getMessage());
}
finally
{
if (connection != null)
{
connection.disconnect();
}
}
}