bad request:Volley 400 - header

i want to connect to server by REST but i have Volley 400 error;
i tried almost everything i could find but nothing;
i'll be grateful if help me!
here is my codes:
private void volleyCall(String phone, String token) {
RequestQueue queue = Volley.newRequestQueue(this);
String URL = "http://1*4.***.**.1*1/login/register-phone";
Map<String, String> jsonParams = new HashMap<>();
jsonParams.put("phone", phone);
jsonParams.put("admin_token", token);
Log.i("log1", "Json:" + new JSONObject(jsonParams));
JsonObjectRequest postRequest = new
JsonObjectRequest(Request.Method.POST, URL,new JSONObject(jsonParams),
new Response.Listener<JSONObject>() {
#Override
public void onResponse(JSONObject response) {
Log.i("log2", "Json" + response);
}
},
new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
// Handle Error
Log.i("log3", "Error: " + error
+ "\nStatus Code " +
error.networkResponse.statusCode
+ "\nResponse Data " +
error.networkResponse.data
+ "\nCause " + error.getCause()
+ "\nmessage" + error.getMessage());
}
}) {
#Override
public Map<String, String> getHeaders() throws AuthFailureError {
HashMap<String, String> headers = new HashMap<String, String>();
headers.put("Content-Type", "application/json; charset=utf-8");
Log.i("log4",headers.toString());
return headers;
}
#Override
public String getBodyContentType() {
return "application/json";
}
};
queue.add(postRequest);
}
someone told me should remove this form header : (and i tried too, But same error!)
headers.put("Content-Type", "application/json; charset=utf-8");

Related

How do i get data from Rest API

Please, i am trying to access data from rest API,
From the Documentation ,to get the token, i have to make a post call ,then use the token received to access two other results:
for the token, they gave this from the documentation:
https://apps.qa.interswitchng.com/passport/oauth/token
with the following Query Params
grant_type string
Headers
Authorization string required
Set value to "Basic Base64(CLIENT_ID:SECRET_KEY)"
Content-Type application/x-www-form-urlencoded
string
My Codes
#SuppressLint("StaticFieldLeak")
class SendTokenReqAsyncTask extends AsyncTask<String, Void, String> {
#Override
protected void onPreExecute() {
super.onPreExecute();
progressDialog = new ProgressDialog(MainActivity.this);
progressDialog.setMessage("processing Token");
progressDialog.setCancelable(false);
progressDialog.show();
}
#Override
protected String doInBackground(String... params) {
JSONObject jsonObject2 = new JSONObject();
InputStream inputStream = null;
String result2 = "";
base64EncodedCredentials = "Basic" + Base64.encodeToString ((CLIENT_ID + ":" + SECRET) .getBytes (), Base64.NO_WRAP);
try {
HttpClient httpclient = new DefaultHttpClient();
HttpPost httpPost = new HttpPost(" https://apps.qa.interswitchng.com/passport/oauth/token/");
//StringEntity stringEntity2 = new StringEntity(userPhoneNumber);
//httpPost.setEntity(stringEntity2);
httpPost.setHeader("Accept", "application/json");
httpPost.setHeader("Authorization", base64EncodedCredentials);
httpPost.setHeader("Content-type", "application/x-www-form-urlencoded");
HttpResponse httpResponse1 = httpclient.execute(httpPost);
inputStream = httpResponse1.getEntity().getContent();
InputStreamReader inputStreamReader1 = new InputStreamReader(inputStream);
BufferedReader bufferedReader = new BufferedReader(inputStreamReader1);
StringBuilder stringBuilder2 = new StringBuilder();
String bufferedStrChunk = null;
int data = inputStreamReader1.read();
while((bufferedStrChunk = bufferedReader.readLine()) != null){
stringBuilder2.append(bufferedStrChunk);
}
result2=stringBuilder2.toString();
return result2;
} catch (Exception e) {
Log.d("InputStream", e.getLocalizedMessage());
}
return null;
}
#Override
protected void onPostExecute(String result2) {
super.onPostExecute(result2);
progressDialog = new ProgressDialog(MainActivity.this);
progressDialog.setCancelable(true);
progressDialog.hide();
//String re=null;
/*try {
JSONObject jsonObject = new JSONObject(result2);
re = jsonObject.getString(result2);
} catch (JSONException e) {
e.printStackTrace();
}*/
txtInfo = findViewById(R.id.textViewMain);
txtInfo.setVisibility(View.VISIBLE);
txtInfo.setText(MessageFormat.format("Token is :{0}", result2));
}
}
with the below code in the oncreate
SendTokenReqAsyncTask myAsyncTasks = new SendTokenReqAsyncTask();
myAsyncTasks.execute();
i also used retrofit this way
#SuppressWarnings("deprecation")
public class MyRetrofitClient {
protected static MyRetrofitClient myRetrofitClient = null;
private static RetroApis myRetroApis;
private static TokenAPI tokenAPI;
private static Retrofit retrofit = null;
private String tokenFromServer;
String clientID,secret;
private byte[] data64;
String base64=null;
MyRetrofitClient() {
if (retrofit == null) {
retrofit = new Retrofit.Builder()
.baseUrl(TOKEN_URL)
.addConverterFactory(GsonConverterFactory.create())
.build();
}
myRetroApis = retrofit.create(RetroApis.class);
}
public String encodeToBase64() {
clientID= CLIENT_ID1;
secret=SECRET1;
String text = clientID + ":" + secret;
data64 = new byte[0];
data64 = text.getBytes(StandardCharsets.UTF_8);
base64=android.util.Base64.encodeToString(data64, android.util.Base64.DEFAULT);
return base64;
}
static Retrofit getTokenClient() {
String type="application/x-www-form-urlencoded";
String base64String=MyRetrofitClient.myRetrofitClient.encodeToBase64();
RequestBody requestBody = RequestBody.create(MediaType.parse("Content-type"), type);
HttpLoggingInterceptor logging = new HttpLoggingInterceptor();
logging.setLevel(HttpLoggingInterceptor.Level.BASIC);
logging.redactHeader("Authorization");
OkHttpClient httpClient = new OkHttpClient.Builder()
.addInterceptor(logging)
.addNetworkInterceptor(new Interceptor() {
#NotNull
#Override
public Response intercept(#NotNull Interceptor.Chain chain) throws IOException {
Request request = chain.request().newBuilder().addHeader("Authorization", MyRetrofitClient.getInstance().encodeToBase64()).build();
return chain.proceed(request);
}
})
.addNetworkInterceptor(new HttpLoggingInterceptor().setLevel(HttpLoggingInterceptor.Level.BASIC))
.build();
retrofit = new Retrofit.Builder()
.baseUrl(TOKEN_URL)
.addConverterFactory(GsonConverterFactory.create())
.client(httpClient)
.build();
return retrofit;
}
static Retrofit getTCreditReportClient(String tokenFromServer,String userPhoneNumber) {
String type="application/json";
RequestBody requestBody = RequestBody.create(MediaType.parse("Content-type"), type);
HttpLoggingInterceptor logging = new HttpLoggingInterceptor();
logging.setLevel(HttpLoggingInterceptor.Level.BODY);
//logging.setLevel(HttpLoggingInterceptor.Level.BODY);
logging.redactHeader("Authorization");
logging.redactHeader("Content-type");
OkHttpClient httpClient = new OkHttpClient.Builder()
.addInterceptor(logging)
.addNetworkInterceptor(new Interceptor() {
#NotNull
#Override
public Response intercept(#NotNull Interceptor.Chain chain) throws IOException {
Request request = chain.request().newBuilder().addHeader("Authorization", tokenFromServer).build();
//Request request3 = chain.request().newBuilder().method("Content-type", requestBody).build();
return chain.proceed(request);
}
})
.addNetworkInterceptor(new HttpLoggingInterceptor().setLevel(HttpLoggingInterceptor.Level.BODY))
.build();
retrofit = new Retrofit.Builder()
.baseUrl("https://reqres.in")
.addConverterFactory(GsonConverterFactory.create())
.client(httpClient)
.build();
return retrofit;
}
static Retrofit getClient() {
HttpLoggingInterceptor logging = new HttpLoggingInterceptor();
logging.setLevel(HttpLoggingInterceptor.Level.BASIC);
//logging.setLevel(HttpLoggingInterceptor.Level.BODY);
logging.redactHeader("Authorization");
logging.redactHeader("Cookie");
OkHttpClient client = new OkHttpClient.Builder()
.addInterceptor(logging)
.build();
retrofit = new Retrofit.Builder()
.baseUrl("https://reqres.in")
.addConverterFactory(GsonConverterFactory.create())
.client(client)
.build();
return retrofit;
}
public static synchronized MyRetrofitClient getInstance() {
if (myRetrofitClient == null) {
myRetrofitClient = new MyRetrofitClient();
}
return myRetrofitClient;
}
public RetroApis getMyApi() {
return myRetroApis;
}
public TokenAPI getMyTokenApi() {
return tokenAPI;
}
}
public interface TokenAPI {
String contentType= "application/json";
String authorization= "<>";
#FormUrlEncoded
#POST("client_credentials")
Call<OAuthToken> postCredentials(#Field("grant_type") String grantType);
//#FormUrlEncoded
#GET("creditScores")
Call<CreditScore> getCreditScore(#Query("client_credentials") String queryParam);
//#FormUrlEncoded
#GET("creditScores")
Call<List<CreditScoreHistory>> getCreditScoreHistory(#Query("client_credentials") String name);
#GET("/1.1/users/show.json")
Call<String> getUserDetails(#Query("screen_name") String name);
}
private void createInterSwitchTokenAPI33() {
editText = findViewById(R.id.editText);
base64EncodedCredentials = "Basic" + Base64.encodeToString ((CLIENT_ID + ":" + SECRET) .getBytes (), Base64.NO_WRAP);
//base64String=this.encodeToBase64();
String editTextInput = Objects.requireNonNull(editText.getText()).toString();
HttpLoggingInterceptor logging = new HttpLoggingInterceptor();
logging.setLevel(HttpLoggingInterceptor.Level.BASIC);
logging.redactHeader("Authorization");
OkHttpClient httpClient = new OkHttpClient.Builder()
.addInterceptor(logging)
.addNetworkInterceptor(new Interceptor() {
#NotNull
#Override
public okhttp3.Response intercept(#NotNull Interceptor.Chain chain) throws IOException {
Request request = chain.request().newBuilder().addHeader("Authorization", base64EncodedCredentials).build();
return chain.proceed(request);
}
})
.addNetworkInterceptor(new HttpLoggingInterceptor().setLevel(HttpLoggingInterceptor.Level.BASIC))
.build();
Retrofit retrofit = new Retrofit.Builder()
.baseUrl(TOKEN_URL)
.addConverterFactory(GsonConverterFactory.create())
.client(httpClient)
.build();
tokenAPI = retrofit.create(TokenAPI.class);
tokenAPI.getCreditScore(editTextInput).enqueue(creditScoreCallback);
}
public void onClick(View view) {
if (view.getId() == R.id.post) {
editText = findViewById(R.id.editText);
String editTextInput = editText.getText().toString();
if (!editTextInput.isEmpty())
createCreditScoreAPI(token);
createHistoryAPI(token);
tokenAPI.getCreditScore(editTextInput).enqueue(creditScoreCallback);
tokenAPI.getCreditScoreHistory(editTextInput).enqueue(creditScoreHistoryCallback);
} else {
Toast.makeText(this, "Please provide your BVN Phone Number", Toast.LENGTH_LONG).show();
}
}
private void createCreditScoreAPI(OAuthToken token) {
OkHttpClient okHttpClient = new OkHttpClient.Builder().addInterceptor(new Interceptor() {
#NotNull
#Override
public okhttp3.Response intercept(#NotNull Chain chain) throws IOException {
//Request originalRequest = chain.request();
Request request = chain.request().newBuilder().addHeader("Authorization", token.getAccessToken()).build();
return chain.proceed(request);
}
}).addNetworkInterceptor(new HttpLoggingInterceptor().setLevel(HttpLoggingInterceptor.Level.HEADERS))
.build();
Retrofit retrofit = new Retrofit.Builder()
.baseUrl(SCORE_URL)
.client(okHttpClient)
.addConverterFactory(GsonConverterFactory.create())
.build();
tokenAPI = retrofit.create(TokenAPI.class);
}
Callback<CreditScore> creditScoreCallback = new Callback<CreditScore>() {
#Override
public void onResponse(Call<CreditScore> call, Response<CreditScore> response) {
if (response.isSuccessful()) {
CreditScore creditScore = response.body();
if (creditScore != null) {
id = creditScore.getId();
msisdn = creditScore.getMsisdn();
score = creditScore.getScore();
dateCreated = creditScore.getDateCreated();
}
displayResponse += id + " Phone\n" + msisdn + " Score\n" + score + " dateCreated\n"+dateCreated;
txtCreditScore = findViewById(R.id.textCreditScore);
if (displayResponse == null) txtCreditScore.setText("no value");
else txtCreditScore.setText(displayResponse);
} else {
Toast.makeText(MainActivity.this, "Failure while requesting Credit Score", Toast.LENGTH_LONG).show();
txtCreditScore.setText(MessageFormat.format("Error!{0}", response.message()));
Log.d("Credit Score Details", "Code: " + response.code() + "Message: " + response.message());
}
}
#Override
public void onFailure(Call<CreditScore> call, Throwable t) {
t.printStackTrace();
}
};
private void createHistoryAPI(OAuthToken token) {
OkHttpClient okHttpClient = new OkHttpClient.Builder().addInterceptor(new Interceptor() {
#NotNull
#Override
public okhttp3.Response intercept(#NotNull Chain chain) throws IOException {
Request originalRequest = chain.request();
Request request = chain.request().newBuilder().addHeader("Authorization", token.getAccessToken()).build();
return chain.proceed(request);
}
}).addNetworkInterceptor(new HttpLoggingInterceptor().setLevel(HttpLoggingInterceptor.Level.HEADERS))
.build();
Retrofit retrofit = new Retrofit.Builder()
.baseUrl(HISTORY_URL)
.client(okHttpClient)
.addConverterFactory(GsonConverterFactory.create())
.build();
tokenAPI = retrofit.create(TokenAPI.class);
}
Callback<List<CreditScoreHistory>> creditScoreHistoryCallback = new Callback<List<CreditScoreHistory>>() {
#Override
public void onResponse(Call<List<CreditScoreHistory>> call, Response<List<CreditScoreHistory>> response) {
if (response.isSuccessful()) {
recyclerView = findViewById(R.id.recyclerViewHistory);
} else {
Toast.makeText(MainActivity.this, "Failure while requesting user details", Toast.LENGTH_LONG).show();
Log.d("History Callback", "Code: " + response.code() + "Message: " + response.message());
}
if (response.isSuccessful()) {
CreditScoreHistory creditScoreHistory = new CreditScoreHistory();
creditScoreList = response.body();
if (creditScoreList != null) {
for (int i = 0; i < creditScoreList.size(); i++) {
creditScoreList.add(creditScoreHistory);
count=creditScoreList.size();
}
if(creditScoreHistory !=null){
msisdn = creditScoreHistory.getMsisdn1();
score = creditScoreHistory.getScore1();
dateCreated = creditScoreHistory.getDateCreated1();
creditScoreList = creditScoreHistory.data;
}
}
displayResponse += count+" Phone\n" + msisdn + " Score\n" + score + " dateCreated\n"+dateCreated;
txtCreditHistory = findViewById(R.id.textCreditHistory);
creditHistoryAdapter = new CreditHistoryAdapter(MainActivity.this, creditScoreList);
LinearLayoutManager linearLayoutManager = new LinearLayoutManager(MainActivity.this);
recyclerView.setLayoutManager(linearLayoutManager);
recyclerView.setItemAnimator(new DefaultItemAnimator());
recyclerView.setAdapter(creditHistoryAdapter);
SnapHelper snapHelper = new PagerSnapHelper();
snapHelper.attachToRecyclerView(recyclerView);
recyclerView.setNestedScrollingEnabled(false);
if (displayResponse == null) txtCreditScore.setText("no value");
else txtCreditHistory.setText(displayResponse);
} else {
Toast.makeText(MainActivity.this, "Failure while requesting Credit Score", Toast.LENGTH_LONG).show();
txtCreditHistory.setText(MessageFormat.format("Error!{0}", response.message()));
Log.d("Credit Score History", "Code: " + response.code() + "Message: " + response.message());
}
}
#Override
public void onFailure(Call<List<CreditScoreHistory>> call, Throwable t) {
t.printStackTrace();
}
};
buy could not get any result, please help
Use VSCode and ThunderClient extension https://marketplace.visualstudio.com/items?itemName=rangav.vscode-thunder-client

API Chorus Pro Oauth2 authentication in Java

I created an account on https://developer.aife.economie.gouv.fr/ website and I want to try API on the sandbox. For this an application has been generated
For this application, I obtain API key and OAuth2 Credentials. Here are my previous API keys.
By reading the documentation, I have the following entry points for authentication
My objective is to get authenticated and get an auth token in order to consume this API. Here is my code:
package com.oauth.app;
import org.apache.oltu.oauth2.client.OAuthClient;
import org.apache.oltu.oauth2.client.URLConnectionClient;
import org.apache.oltu.oauth2.client.request.OAuthClientRequest;
import org.apache.oltu.oauth2.client.response.OAuthJSONAccessTokenResponse;
import org.apache.oltu.oauth2.common.OAuth;
import org.apache.oltu.oauth2.common.exception.OAuthProblemException;
import org.apache.oltu.oauth2.common.exception.OAuthSystemException;
import org.apache.oltu.oauth2.common.message.types.GrantType;
import javax.net.ssl.HttpsURLConnection;
import javax.net.ssl.SSLContext;
import javax.net.ssl.TrustManager;
import javax.net.ssl.X509TrustManager;
import java.security.SecureRandom;
import java.security.cert.X509Certificate;
public class OAuthApp {
/**
* URL for requesting OAuth access tokens.
*/
private static final String TOKEN_REQUEST_URL =
"https://sandbox-oauth.aife.economie.gouv.fr/api/oauth/token";
/**
* Client ID of your client credential. Change this to match whatever credential you have created.
*/
private static final String CLIENT_ID =
"1f80aa43-e12f-4e1c-ad42-87ec16baf060";
/**
* Client secret of your client credential. Change this to match whatever credential you have created.
*/
private static final String CLIENT_SECRET =
"a232af0e-513e-4a64-9977-410d237dc421";
/**
* Account on which you want to request a resource. Change this to match the account you want to
* retrieve resources on.
*/
private static final String ACCOUNT_ID =
"a232af0e-513e-4a64-9977-410d237dc421";
/**
* Request a fresh access token using the given client ID, client secret, and token request URL,
* then request the resource at the given resource URL using that access token, and get the resource
* content. If an exception is thrown, print the stack trace instead.
*
* #param args Command line arguments are ignored.
*/
public static void main(String[] args) {
try {
OAuthClient client = new OAuthClient(new URLConnectionClient());
System.out.println("OAuthClient " + client.toString());
OAuthClientRequest request =
OAuthClientRequest.tokenLocation(TOKEN_REQUEST_URL)
.setGrantType(GrantType.CLIENT_CREDENTIALS)
.setClientId(CLIENT_ID)
.setClientSecret(CLIENT_SECRET)
// .setScope() here if you want to set the token scope
.buildQueryMessage();
request.addHeader("Accept", "application/json");
// request.addHeader("Content-Type", "application/json");
// request.addHeader("Authorization", base64EncodedBasicAuthentication());
System.out.println("OAuthClientRequest body\n\t " + request.getBody());
System.out.println("OAuthClientRequest headers\n\t " + request.getHeaders());
System.out.println("OAuthClientRequest locationUri\n\t " + request.getLocationUri());
// Create a trust manager that does not validate certificate chains
TrustManager[] trustAllCerts = new TrustManager[]{new X509TrustManager() {
public X509Certificate[] getAcceptedIssuers() {
return null;
}
public void checkClientTrusted(X509Certificate[] certs, String authType) {
}
public void checkServerTrusted(X509Certificate[] certs, String authType) {
}
}};
// Install the all-trusting trust manager
try {
SSLContext sc = SSLContext.getInstance("TLS");
sc.init(null, trustAllCerts, new SecureRandom());
HttpsURLConnection.setDefaultSSLSocketFactory(sc.getSocketFactory());
} catch (Exception e) {
e.printStackTrace();
}
String token = client.accessToken(
request,
OAuth.HttpMethod.GET,
OAuthJSONAccessTokenResponse.class).getAccessToken();
} catch (OAuthSystemException | OAuthProblemException e) {
e.printStackTrace();
}
}
}
I obtain this in my console:
OAuthClient org.apache.oltu.oauth2.client.OAuthClient#7e0ea639
OAuthClientRequest body
null
OAuthClientRequest headers
{Accept=application/json, Content-Type=application/json}
OAuthClientRequest locationUri
https://sandbox-oauth.aife.economie.gouv.fr/api/oauth/token?grant_type=client_credentials&client_secret=a232af0e-513e-4a64-9977-410d237dc421&client_id=42b214ec-7eaf-4f37-aeb5-ae91057a0e27
OAuthProblemException{error='unsupported_response_type', description='Invalid response! Response body is not application/json encoded', uri='null', state='null', scope='null', redirectUri='null', responseStatus=0, parameters={}}
at org.apache.oltu.oauth2.common.exception.OAuthProblemException.error(OAuthProblemException.java:63)
at org.apache.oltu.oauth2.client.response.OAuthJSONAccessTokenResponse.setBody(OAuthJSONAccessTokenResponse.java:76)
at org.apache.oltu.oauth2.client.response.OAuthClientResponse.init(OAuthClientResponse.java:92)
at org.apache.oltu.oauth2.client.response.OAuthAccessTokenResponse.init(OAuthAccessTokenResponse.java:65)
at org.apache.oltu.oauth2.client.response.OAuthClientResponse.init(OAuthClientResponse.java:101)
at org.apache.oltu.oauth2.client.response.OAuthAccessTokenResponse.init(OAuthAccessTokenResponse.java:60)
at org.apache.oltu.oauth2.client.response.OAuthClientResponse.init(OAuthClientResponse.java:120)
at org.apache.oltu.oauth2.client.response.OAuthClientResponseFactory.createCustomResponse(OAuthClientResponseFactory.java:82)
at org.apache.oltu.oauth2.client.URLConnectionClient.execute(URLConnectionClient.java:111)
at org.apache.oltu.oauth2.client.OAuthClient.accessToken(OAuthClient.java:65)
at com.oauth.app.OAuthApp.main(OAuthApp.java:101)
I obtain this error message:
OAuthProblemException{error='unsupported_response_type', description='Invalid response! Response body is not application/json encoded'
I also tried to use a curl call to the API :
curl –k –H "content-type :application/x-www-form-urlencoded" –d "grant_type=client_credentials&client_id=42b214ec-7eaf-4f37-aeb5-ae91057a0e27&client_secret=a232af0e-513e-4a64-9977-410d237dc421&scope=openid" –X POST https://sandbox-oauth.aife.finances.rie.gouv.fr/api/oauth/token
curl: (6) Could not resolve host: -k
curl: (6) Could not resolve host: -H
curl: (3) Port number ended with 'a'
curl: (6) Could not resolve host: -d
curl: (6) Could not resolve host: grant_type=client_credentials&client_id=42b214ec-7eaf-4f37-aeb5-ae91057a0e27&client_secret=a232af0e-513e-4a64-9977-410d237dc421&scope=openid
curl: (6) Could not resolve host: -X
curl: (6) Could not resolve host: POST
curl: (6) Could not resolve host: sandbox-oauth.aife.finances.rie.gouv.fr
Ok i finally solved my own issue. There was no need to use OAuth stuff.
It's divided onto 2 classes. This code is just for testing purpose.
public class OAuthApp {
private static final String TOKEN_REQUEST_URL = "https://sandbox-oauth.aife.economie.gouv.fr/api/oauth/token";
private static final String CLIENT_ID = "xxxxxx";
private static final String CLIENT_SECRET = "xxxxxx";
private static final String GRANT_TYPE = "client_credentials";
private static final String SCOPE = "openid";
public static void main(String[] args) throws IOException {
try {
Map<String, String> headers = new HashMap<>();
HttpsPostForm httpsPostForm = new HttpsPostForm(TOKEN_REQUEST_URL, "utf-8", headers);
httpsPostForm.addFormField("grant_type", GRANT_TYPE);
httpsPostForm.addFormField("client_id", CLIENT_ID);
httpsPostForm.addFormField("client_secret", CLIENT_SECRET);
httpsPostForm.addFormField("scope", SCOPE);
// Result
String response = httpsPostForm.finish();
System.out.println(response);
} catch (IOException e) {
e.printStackTrace();
}
}
}
My second class is just building the HTTPS request and set the headers elements. The empty trust manager helps to avoid error messages.
public class HttpsPostForm {
private HttpsURLConnection conn;
private Map<String, Object> queryParams;
private String charset;
public HttpsPostForm(String requestURL, String charset, Map<String, String> headers, Map<String, Object> queryParams) throws IOException {
this.charset = charset;
if (queryParams == null) {
this.queryParams = new HashMap<>();
} else {
this.queryParams = queryParams;
}
// Create a trust manager that does not validate certificate chains
TrustManager[] trustAllCerts = new TrustManager[]{new X509TrustManager() {
public X509Certificate[] getAcceptedIssuers() {
return null;
}
public void checkClientTrusted(X509Certificate[] certs, String authType) {
}
public void checkServerTrusted(X509Certificate[] certs, String authType) {
}
}};
// Install the all-trusting trust manager
try {
SSLContext sc = SSLContext.getInstance("TLS");
sc.init(null, trustAllCerts, new SecureRandom());
HttpsURLConnection.setDefaultSSLSocketFactory(sc.getSocketFactory());
} catch (Exception e) {
e.printStackTrace();
}
URL url = new URL(requestURL);
conn = (HttpsURLConnection) url.openConnection();
conn.setUseCaches(false);
conn.setDoOutput(true); // indicates POST method
conn.setDoInput(true);
conn.setRequestProperty("Content-Type", "application/x-www-form-urlencoded");
if (headers != null && headers.size() > 0) {
Iterator<String> it = headers.keySet().iterator();
while (it.hasNext()) {
String key = it.next();
String value = headers.get(key);
conn.setRequestProperty(key, value);
}
}
}
public HttpsPostForm(String requestURL, String charset, Map<String, String> headers) throws IOException {
this(requestURL, charset, headers, null);
}
public HttpsPostForm(String requestURL, String charset) throws IOException {
this(requestURL, charset, null, null);
}
public void addFormField(String name, Object value) {
queryParams.put(name, value);
}
public void addHeader(String key, String value) {
conn.setRequestProperty(key, value);
}
private byte[] getParamsByte(Map<String, Object> params) {
byte[] result = null;
StringBuilder postData = new StringBuilder();
for (Map.Entry<String, Object> param : params.entrySet()) {
if (postData.length() != 0) {
postData.append('&');
}
postData.append(this.encodeParam(param.getKey()));
postData.append('=');
postData.append(this.encodeParam(String.valueOf(param.getValue())));
}
try {
result = postData.toString().getBytes("UTF-8");
} catch (UnsupportedEncodingException e) {
e.printStackTrace();
}
return result;
}
private String encodeParam(String data) {
String result = "";
result = URLEncoder.encode(data, StandardCharsets.UTF_8);
return result;
}
public String finish() throws IOException {
String response = "";
byte[] postDataBytes = this.getParamsByte(queryParams);
conn.getOutputStream().write(postDataBytes);
// Check the http status
int status = conn.getResponseCode();
if (status == HttpsURLConnection.HTTP_OK) {
ByteArrayOutputStream result = new ByteArrayOutputStream();
byte[] buffer = new byte[1024];
int length;
while ((length = conn.getInputStream().read(buffer)) != -1) {
result.write(buffer, 0, length);
}
response = result.toString(this.charset);
conn.disconnect();
} else {
throw new IOException("Server returned non-OK status: " + status);
}
return response;
}
}
Finally I can print my Json string :
{
"access_token":"Js1NYJvtQREj0I0Dz5b0qrMh8gjJBlltJAit2Yx6BGJDloixPv2JwB",
"token_type":"Bearer",
"expires_in":3600,
"scope":"openid resource.READ"
}
I also had some difficulties with Chorus API but I achieve to get the tokenKey with that with the same method but buildBodyMessage() at the end.
// Création requête pour obtenir le token Oauth2 API CHORUS
request = OAuthClientRequest
.tokenLocation(urlToken)
.setGrantType(GrantType.CLIENT_CREDENTIALS)
.setClientId(clientid)
.setClientSecret(clientsecret)
.setScope(OidcScopes.OPENID)
.buildBodyMessage();
// Ajout du Cpro-account
request.addHeader("cpro-account", cproAccount);
tokenChorus = client.accessToken(request, OAuth.HttpMethod.POST, OAuthJSONAccessTokenResponse.class)
.getAccessToken();
that create token formated in String. And afterthat you must create HttpUrlConnection with this token with headers like that
HttpURLConnection connexion = null;
try {
URL url = new URL(currentUrl);
connexion = (HttpURLConnection) url.openConnection();
} catch (IOException e) {
e.printStackTrace();
}
connexion.setRequestProperty("Content-type", "application/json");
connexion.setRequestProperty("Authorization", "Bearer " + tokenChorus);
connexion.setRequestProperty("cpro-account", cproAccount);
try {
connexion.setRequestMethod("POST");
} catch (ProtocolException e) {
e.printStackTrace();
}
connexion.setDoInput(true);
connexion.setDoOutput(true);
return connexion;

Null pointer Exception when using volley

i am using volley to fetch data from database.I always get null pointer error. I don't know whats the error. it always executes onErrorResponse() (error.null) and shows this in my logcat
BasicNetwork.performRequest: Unexpected response code 301
here is my java method to fetch data from php file .
private void fetchChatThread() {
StringRequest strReq = new StringRequest(Request.Method.POST,
EndPoints.chatMessages, new Response.Listener<String>() {
#Override
public void onResponse(String response) {
try {
JSONObject obj = new JSONObject(response);
Load_datato_list load_data_tolist = new Load_datato_list();
load_data_tolist.execute(obj);
} catch (JSONException e) {
Log.e(TAG, "json parsing error: " + e.getMessage());
}
}
}, new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
Messages messages=new Messages();
error.printStackTrace();
NetworkResponse networkResponse = error.networkResponse;
Log.e(TAG, " Try Again fetch error" + networkResponse);
Toast.makeText(Chat_Rooms.this, messages.getSender_id(), Toast.LENGTH_SHORT).show();
}
}) {
#Override
protected Map<String, String> getParams() {
Map<String, String> myparams = new HashMap<String, String>();
try {
myparams.put("sender_userid", sender_userid);
myparams.put("reciver_id", String_username.reciver_user_id);
} catch (Exception e) {
e.printStackTrace();
}
Log.e(TAG, "Params: " + myparams.toString());
return myparams;
}
};
//Adding request to request queue
addToRequestQueue(strReq);
}
here is my private that loads data from php to objects
private class Load_datato_list extends AsyncTask<JSONObject, Void, ArrayList<Messages>> {
#Override
protected ArrayList<Messages> doInBackground(JSONObject[] params) {
JSONObject obj = params[0];
try {
JSONArray commentsObj = obj.getJSONArray("messages");
for (int i = 0; i < commentsObj.length(); i++) {
JSONObject commentObj = (JSONObject) commentsObj.get(i);
String commentId = commentObj.getString("id");
String commentText = commentObj.getString("message");
String createddate = commentObj.getString("date");
String commentuser_id = commentObj.getString("user_id_fk");
URL url;
Bitmap image, image1;
try {
url = new URL(Base_URL.BASE_URL_IMAGES + "user_profile_pictures" + commentuser_id + ".jpg");
image1 = BitmapFactory.decodeStream(url.openStream());
image = getResizedBitmap(image1, 50);
} catch (Exception e) {
image = null;
e.printStackTrace();
}
Users user;
user = new Users(commentuser_id, String_username.user_name, image);
Messages message = new Messages();
message.setId(commentId);
message.setMessage(commentText);
message.setCreatedAt(createddate);
message.setSender_id(commentuser_id);
message.setUser(user);
messageArrayList.add(message);
}
} catch (Exception e) {
e.printStackTrace();
}
return messageArrayList;
}
#Override
protected void onPostExecute(ArrayList<Messages> messageArrayList) {
Collections.reverse(messageArrayList);
chatroom_adapter.notifyDataSetChanged();
if (chatroom_adapter.getItemCount() > 1) {
rec_chatBubble.getLayoutManager().smoothScrollToPosition(rec_chatBubble, null, chatroom_adapter.getItemCount() - 1);
}
}
}
TRY THIS
private void fetchChatThread(final String count) {
StringRequest strReq = new StringRequest(Request.Method.POST,
EndPoints.chatMessages, new Response.Listener<String>() {
#Override
public void onResponse(String response) {
try {
JSONObject obj = new JSONObject(response);
Log.d("response error", response);
Load_datato_list load_data_tolist = new Load_datato_list();
load_data_tolist.execute(obj);
} catch (JSONException e) {
Log.e(TAG, "json parsing error: " + e.getMessage());
}
}
}, new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
Messages messages = new Messages();
error.printStackTrace();
NetworkResponse networkResponse = error.networkResponse;
Log.e(TAG, " Try Again fetch error" + networkResponse);
}
}) {
#Override
protected HashMap<String, String> getParams() {
HashMap<String, String> myparams = new HashMap<String, String>();
try {
myparams.put("sender_userid", sender_userid);
myparams.put("reciver_id", String_username.reciver_user_id);
myparams.put("count", count);
} catch (Exception e) {
e.printStackTrace();
}
Log.e(TAG, "Params: " + myparams.toString());
return myparams;
}
};
//Adding request to request queueok
addToRequestQueue(strReq);
}
AND THIS
private class Load_datato_list extends AsyncTask<JSONObject, Void, ArrayList<Messages>> {
#Override
protected ArrayList<Messages> doInBackground(JSONObject[] params) {
messageArrayList.clear();
JSONObject obj = params[0];
try {
JSONArray commentsObj = obj.getJSONArray("messages");
for (int i = 0; i < commentsObj.length(); i++) {
JSONObject commentObj = (JSONObject) commentsObj.get(i);
String Id = commentObj.getString("id");
String Text = commentObj.getString("message");
String date = commentObj.getString("date");
String yuser_id = commentObj.getString("user_id");
Messages message = new Messages();
message.setId(Id);
message.setMessage(Text);
message.setCreatedAt(date);
message.setSender_id(yuser_id);
messageArrayList.add(message);
}
} catch (Exception e) {
e.printStackTrace();
}
return messageArrayList;
}

NPE when trying to use Jetty async HTTP client

When trying to use Firebase Cloud Messaging by Google with the help of non-blocking Jetty HTTP client in a simple test case that I have prepared at GitHub -
private static final HttpClient sHttpClient = new HttpClient();
private static final Response.ContentListener sFcmListener = new Response.ContentListener() {
#Override
public void onContent(Response response, ByteBuffer content) {
if (response.getStatus() != 200) {
return;
}
String body = StandardCharsets.UTF_8.decode(content).toString();
System.out.printf("onContent: %s\n", body);
Map<String, Object> resp = (Map<String, Object>) JSON.parse(body);
try {
Object[] results = (Object[]) resp.get(FCM_RESULTS);
Map result = (Map) results[0];
String error = (String) result.get(FCM_ERROR);
if (FCM_NOT_REGISTERED.equals(error)) {
// TODO delete invalid FCM token from the database
}
} catch (Exception ignore) {
}
}
};
public static void main(String[] args) throws Exception {
sHttpClient.start();
sHttpClient.POST(FCM_URL)
.header(HttpHeader.AUTHORIZATION, FCM_KEY)
.header(HttpHeader.CONTENT_TYPE, "application/json")
.content(new StringContentProvider(JSON.toString(REQUEST)))
.onResponseContent(sFcmListener)
.send();
}
but unfortunately the execution fails immediately with NPE:
2017-06-30 10:46:41.312:INFO::main: Logging initialized #168ms to org.eclipse.jetty.util.log.StdErrLog
Exception in thread "main" java.util.concurrent.ExecutionException: java.lang.NullPointerException
at org.eclipse.jetty.client.util.FutureResponseListener.getResult(FutureResponseListener.java:118)
at org.eclipse.jetty.client.util.FutureResponseListener.get(FutureResponseListener.java:101)
at org.eclipse.jetty.client.HttpRequest.send(HttpRequest.java:682)
at de.afarber.fcmnotregistered.Main.main(Main.java:68)
Caused by: java.lang.NullPointerException
at org.eclipse.jetty.io.ssl.SslClientConnectionFactory.newConnection(SslClientConnectionFactory.java:59)
at org.eclipse.jetty.client.AbstractHttpClientTransport$ClientSelectorManager.newConnection(AbstractHttpClientTransport.java:191)
at org.eclipse.jetty.io.ManagedSelector.createEndPoint(ManagedSelector.java:420)
at org.eclipse.jetty.io.ManagedSelector.access$1600(ManagedSelector.java:61)
at org.eclipse.jetty.io.ManagedSelector$CreateEndPoint.run(ManagedSelector.java:599)
at org.eclipse.jetty.util.thread.Invocable.invokePreferred(Invocable.java:128)
at org.eclipse.jetty.util.thread.Invocable$InvocableExecutor.invoke(Invocable.java:222)
at org.eclipse.jetty.util.thread.strategy.EatWhatYouKill.doProduce(EatWhatYouKill.java:294)
at org.eclipse.jetty.util.thread.strategy.EatWhatYouKill.run(EatWhatYouKill.java:199)
at org.eclipse.jetty.util.thread.QueuedThreadPool.runJob(QueuedThreadPool.java:672)
at org.eclipse.jetty.util.thread.QueuedThreadPool$2.run(QueuedThreadPool.java:590)
at java.lang.Thread.run(Thread.java:745)
Why does it happen please?
UPDATE:
I have switched to using BufferingResponseListener and the NPE is gone, but now the program prints java.net.NoRouteToHostException: No route to host even though the Google FCM endpoint is a well-known host:
private static final HttpClient sHttpClient = new HttpClient();
private static final BufferingResponseListener sFcmListener = new BufferingResponseListener() {
#Override
public void onComplete(Result result) {
if (!result.isSucceeded()) {
System.err.println(result.getFailure()); // No route to host
return;
}
String body = getContentAsString(StandardCharsets.UTF_8);
System.out.printf("onContent: %s\n", body);
Map<String, Object> resp = (Map<String, Object>) JSON.parse(body);
try {
Object[] results = (Object[]) resp.get(FCM_RESULTS);
Map map = (Map) results[0];
String error = (String) map.get(FCM_ERROR);
if (FCM_NOT_REGISTERED.equals(error)) {
// TODO delete invalid FCM token from the database
}
} catch (Exception ex) {
System.err.println(ex);
}
}
};
public static void main(String[] args) throws Exception {
sHttpClient.start();
sHttpClient.POST(FCM_URL)
.header(HttpHeader.AUTHORIZATION, FCM_KEY)
.header(HttpHeader.CONTENT_TYPE, "application/json")
.content(new StringContentProvider(JSON.toString(REQUEST)))
.send(sFcmListener);
}
I get the No route to host for any FCM_URL value I try, why?
Adding SslContextFactory has helped me:
private static final SslContextFactory sFactory = new SslContextFactory();
private static final HttpClient sHttpClient = new HttpClient(sFactory);
private static final BufferingResponseListener sFcmListener = new BufferingResponseListener() {
#Override
public void onComplete(Result result) {
if (!result.isSucceeded()) {
System.err.println(result.getFailure());
return;
}
String body = getContentAsString(StandardCharsets.UTF_8);
System.out.printf("onComplete: %s\n", body);
try {
Map<String, Object> resp = (Map<String, Object>) JSON.parse(body);
Object[] results = (Object[]) resp.get(FCM_RESULTS);
Map map = (Map) results[0];
String error = (String) map.get(FCM_ERROR);
System.out.printf("error: %s\n", error);
if (FCM_NOT_REGISTERED.equals(error) ||
FCM_MISSING_REGISTRATION.equals(error) ||
FCM_INVALID_REGISTRATION.equals(error)) {
// TODO delete invalid FCM token from the database
}
} catch (Exception ex) {
System.err.println(ex);
}
}
};
public static void main(String[] args) throws Exception {
sHttpClient.start();
sHttpClient.POST(FCM_URL)
.header(HttpHeader.AUTHORIZATION, FCM_KEY)
.header(HttpHeader.CONTENT_TYPE, "application/json")
.content(new StringContentProvider(JSON.toString(REQUEST)))
.send(sFcmListener);
}
The still open question I have is how to retrieve the invalid FCM token that I have used in the Jetty HTTP client request, so that I can delete it from my database on the response...

HTTP Requests in Glass GDK

I am implementing a GDK application and need to do in my application some HTTP Post requests. Do I send the HTTP requests the same way as on android phone or there is some other way of doing it? (I have tried the code that I am using on my phone and it's not working for glass.)
thanks for your help in advance.
You can make any post request like in smartphones, but ensure you make the requests using an AsyncTask.
For example:
private class SendPostTask extends AsyncTask<Void, Void, Void> {
#Override
protected Void doInBackground(Void... params) {
// Make your request POST here. Example:
myRequestPost();
return null;
}
protected void onPostExecute(Void result) {
// Do something when finished.
}
}
And you can call that asynctask anywhere with:
new SendPostTask().execute();
And example of myRequestPost() may be:
private int myRequestPost() {
int resultCode = 0;
String url = "http://your-url-here";
HttpClient client = new DefaultHttpClient();
HttpPost post = new HttpPost(url);
// add headers you want, example:
// post.setHeader("Authorization", "YOUR-TOKEN");
List<NameValuePair> urlParameters = new ArrayList<NameValuePair>();
nameValuePairs.add(new BasicNameValuePair("id", "111111"));
nameValuePairs.add(new BasicNameValuePair("otherField", "your-other-data"));
try {
post.setEntity(new UrlEncodedFormEntity(urlParameters));
HttpResponse response = client.execute(post);
System.out.println("\nSending 'POST' request to URL : " + url);
System.out.println("Post parameters : " + post.getEntity());
System.out.println("Response Code : " +
response.getStatusLine().getStatusCode());
resultCode = response.getStatusLine().getStatusCode();
BufferedReader rd = new BufferedReader(
new InputStreamReader(response.getEntity().getContent()));
StringBuffer result = new StringBuffer();
String line = "";
while ((line = rd.readLine()) != null) {
result.append(line);
}
System.out.println(result.toString());
} catch (Exception e) {
Log.e("POST", e.getMessage());
}
return resultCode;
}