I am building an android app that needs to log the user to our server and the connection needs to be secure (HTTPs). My question is, should I use OKHTTP library for this purpose?
I use the library to log a user as follows:
public class MainActivity extends AppCompatActivity {
public static final MediaType JSON
= MediaType.parse("application/json; charset=utf-8");
private static final String TAG = MainActivity.class.getSimpleName();
private JSONObject responseJson;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar);
setSupportActionBar(toolbar);
final JSONObject myJson = new JSONObject();
try {
myJson.put("udid","c376e418-da42-39fb-0000-d821f1fd2804");
myJson.put("email","email
myJson.put("password","password");
} catch (JSONException e) {
e.printStackTrace();
}
Thread thread = new Thread(new Runnable(){
#Override
public void run() {
try {
//Your code goes here
String response = post("https://ADDRESS/v1/auth", myJson.toString());
responseJson = new JSONObject(response);
String message = responseJson.getString("message");
String token = responseJson.getString("token");
Log.d(TAG,"Response message: " + message);
Log.d(TAG,"Response token: " + token);
Log.d("MainActivity",response);
} catch (Exception e) {
e.printStackTrace();
}
}
});
thread.start();
}
String post(String url, String json) throws IOException {
OkHttpClient client = new OkHttpClient();
RequestBody body = RequestBody.create(JSON, json);
Request request = new Request.Builder()
.url(url)
.post(body)
.build();
Response response = client.newCall(request).execute();
return response.body().string();
}
}
should I use OKHTTP library for this purpose?
OkHttp supports https URLs, as do most HTTP client libraries for Android.
Related
all I need to send the notifications for an app which contains 2 firebase database. from one firebase database I am sending notifications to an app. But app is not receiving the notifications
i have the same problem but resolve using this code
implement this library
implementation 'com.squareup.okhttp3:okhttp:3.4.1'
static OkHttpClient mClient;
static JSONArray jsonArray;
static Context context;
static String messageStr = "";
public static void sendNotification(Context mContext,String mMessage,final JSONArray jsonArray1) {
mClient = new OkHttpClient();
context = mContext;
messageStr = mMessage;
jsonArray = jsonArray1;
new MyTask().execute();
}
static class MyTask extends AsyncTask<String, String, String> {
#Override
protected String doInBackground(String... params) {
try {
for (int i = 0; i < jsonArray.length(); i++) {
JSONObject root = new JSONObject();
JSONObject notification = new JSONObject();
notification.put("text", messageStr);
notification.put("title", "Cell Command");
notification.put("line1", R.mipmap.ic_launcher);
notification.put("line2", "high");
root.put("to", jsonArray.get(i));
root.put("data", notification);
String result = postToFCM(root.toString());
Log.d("Main Activity", "Result: " + result);
return result;
}
} catch (Exception ex) {
ex.printStackTrace();
}
return null;
}
#Override
protected void onPostExecute(String result) {
if (result != null) {
try {
JSONObject resultJson = new JSONObject(result);
} catch (JSONException e) {
e.printStackTrace();
Toast.makeText(context, "" + e.toString(), Toast.LENGTH_SHORT).show();
}
}
}
}
static String postToFCM(String bodyString) throws IOException {
final String FCM_MESSAGE_URL = "https://fcm.googleapis.com/fcm/send";
final MediaType JSON
= MediaType.parse("application/json");
RequestBody body = RequestBody.create(JSON, bodyString);
Request request = new Request.Builder()
.url(FCM_MESSAGE_URL)
.post(body)
.addHeader("Authorization", "key=" + "put your firebase legacy key")
.build();
Response response = mClient.newCall(request).execute();
return response.body().string();
}
inside jsonarray put your device token
hope this will help you.
public class AppApi extends AsyncTask<String, Void, String> {
private OkHttpClient client;
private Request request;
private MediaType JSON;
private String URL;
private RequestBody body;
public AppApi(JSONObject obj) {
client = new OkHttpClient();
JSON = MediaType.parse("application/json; charset=utf-8");
URL = "http://serverapi.domain.com/user/login";
Log.d("Information",obj.toString());
body = RequestBody.create(JSON, obj.toString());
request = new Request.Builder()
.url(URL)
.post(body)
.build();
}
#Override
protected String doInBackground(String... strings) {
// execute fonksiyonu cagrilarak calistirilir
try {
Response response = client.newCall(request).execute();
return response.body().string();
} catch (Exception ex) {
Log.e("doInBackground()", ex.getMessage());
return null;
}
}
protected void onProgressUpdate(Integer... progress) {
// setProgressPercent(progress[0]);
}
protected void onPostExecute(Long result) {
// showDialog("Downloaded " + result + " bytes");
}
}
btnLogin.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
login();
}
}
LoginActivity.Java below.
private void login() {
JSONObject data = new JSONObject();
try {
data.put("email", "email");
data.put("password", "pass");
} catch (JSONException e) {
}
AppApi api = new AppApi(data);
try {
String result = api.execute().get();
Log.d("login()", result);
} catch (Exception e) {
e.printStackTrace();
}
}
So the problem with the application is that we can't properly login to our https server. Android Studio says it is skipping frames.
I/Choreographer: Skipped 77 frames! The application may be doing too
much work on its main thread.
When we try to enter the wrong password intentionally, it skips even more frames.(200ish)
I think we did most of the coding correctly on the Async task side. How can we check the return value? How can we solve the problem?
Try to put the build request into the background thread as well .i.e
private JSONObject obj;
public AppApi(JSONObject obj) {
this.obj = obj;
}
#Override
protected String doInBackground(String... strings) {
// execute fonksiyonu cagrilarak calistirilir
try {
client = new OkHttpClient();
JSON = MediaType.parse("application/json; charset=utf-8");
URL = "http://serverapi.domain.com/user/login";
Log.d("Information",obj.toString());
body = RequestBody.create(JSON, obj.toString());
request = new Request.Builder()
.url(URL)
.post(body)
.build();
Response response = client.newCall(request).execute();
return response.body().string();
} catch (Exception ex) {
Log.e("doInBackground()", ex.getMessage());
return null;
}
}
I have written following code to post and get data from server using okhttp but it is not working.
In NewTest.java
public class NewTest extends AppCompatActivity {
TextView txtJson;
Button btnOkay;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_new_test);
txtJson= (TextView) findViewById(R.id.txtJson);
findViewById(R.id.txtJson)).getText().toString());
assert (findViewById(R.id.btnOkay)) != null;
(findViewById(R.id.btnOkay)).setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
new TaskPostWebService("url written here").execute(((TextView) findViewById(R.id.txtJson)).getText().toString());
}
});
}
private class TaskWebServiceGet extends AsyncTask<String,Void,String> {
#Override
protected void onPreExecute()
{
super.onPreExecute();
}
#Override
protected String doInBackground(String... params) {
try {
OkHttpClient client = new OkHttpClient();
Request request = new Request.Builder()
.url(params[0])
.build();
Response response = client.newCall(request).execute();
String responseJson = response.body().string();
Log.i("#", "" + responseJson);
}
catch (Exception e){
e.printStackTrace();
}
return null;
}
#Override
protected void onPostExecute(String s) {
super.onPostExecute(s);
}
}
private class TaskPostWebService extends AsyncTask<String,Void,String> {
private String url;
private ProgressDialog progressDialog;
public TaskPostWebService(String url ){
this.url = url;
}
#Override
protected void onPreExecute() {
super.onPreExecute();
progressDialog = ProgressDialog.show(NewTest.this,"","");
}
#Override
protected String doInBackground(String... params) {
String fact = "";
try {
OkHttpClient client = new OkHttpClient();
RequestBody body = new FormBody.Builder()
.add("\"nonce\" : \"G9Ivek\",", params[0])
.add("\"iUserId \": \"477\",", params[1])
.build();
Request request = new Request.Builder()
.url(url)
.post(body)
.build();
Response response = client.newCall(request).execute(); // hits server
String json = response.body().string(); // server gives response
ObjectMapper mapper = new ObjectMapper();
Map<String,String> map = mapper.readValue(json, new TypeReference<Map>() { // convert json to object
});
if(map != null){
fact = map.get("gruesomeFact");
}
Log.i("#",""+json);
}
catch (Exception e){
e.printStackTrace();
}
return fact;
}
#Override
protected void onPostExecute(String s) {
super.onPostExecute(s);
TextView text = (TextView) findViewById(R.id.txtJson);
text.setText(s);
progressDialog.dismiss();
}
}
}
I am getting Access denied message.
Can anybody tell me what is wrong.
Try to do the POST request in the following way in your doInBackground() method:
private final MediaType JSON = MediaType.parse("application/json; charset=utf-8");
OkHttpClient client = new OkHttpClient();
//Create a JSONObject with the data to be sent to the server
JSONObject dataToSend = new JSONObject()
.put("nonce", "G9Ivek")
.put("iUserId", "477");
//Create request object
Request request = new Request.Builder()
.url(url)
.post(RequestBody.create(JSON, dataToSend.toString()))
.build();
//Make the request
Response response = client.newCall(request).execute();
//Convert the response to String
String responseData = response.body().string();
//Construct JSONObject of the response string
JSONObject dataReceived = new JSONObject(responseData);
//See the response from the server
Log.i("response data", dataReceived.toString());
Answer to code is as below. it worked.
Now I want to show response in listview. How to do this?
*/
public class NewTest extends AppCompatActivity {
TextView txtJson;
Button btnOkay;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_new_test);
txtJson= (TextView) findViewById(R.id.txtJson);
assert (findViewById(R.id.btnOkay)) != null;
(findViewById(R.id.btnOkay)).setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
new TaskPostWebService("written url here").execute(((TextView)
findViewById(R.id.txtJson)).getText().toString());
}
});
}
private class TaskPostWebService extends AsyncTask<String,Void,String> {
private String url;
private ProgressDialog progressDialog;
private JSONParser jsonParser;
public TaskPostWebService(String url ){
this.url = url;
}
#Override
protected void onPreExecute() {
super.onPreExecute();
progressDialog = ProgressDialog.show(NewTest.this,"","");
}
#Override
protected String doInBackground(String... params) {
String fact = "";
try {
final MediaType JSON = MediaType.parse("application/json");
android.util.Log.e("charset", "charset - " + JSON.charset());
OkHttpClient client = new OkHttpClient();
//Create a JSONObject with the data to be sent to the server
final JSONObject dataToSend = new JSONObject()
.put("nonce", "G9Ivek")
.put("iUserId", "477");
android.util.Log.e("data - ", "data - " + dataToSend.toString());
//Create request object
Request request = new Request.Builder()
.url("written url here")
.post(RequestBody.create(JSON, dataToSend.toString().getBytes(Charset.forName("UTF-8"))))
.addHeader("Content-Type", "application/json")
.build();
android.util.Log.e("request - ", "request - " + request.toString());
android.util.Log.e("headers - ", "headers - " + request.headers().toString());
android.util.Log.e("body - ", "body - " + request.body().toString());
//Make the request
Response response = client.newCall(request).execute();
android.util.Log.e("response", " " + response.body().string()); //Convert the response to String
String responseData = response.body().string();
//Construct JSONObject of the response string
JSONObject dataReceived = new JSONObject(responseData);
//See the response from the server
Log.i("response data", dataReceived.toString());
}
catch (Exception e){
e.printStackTrace();
}
return fact;
}
#Override
protected void onPostExecute(String s) {
super.onPostExecute(s);
TextView text = (TextView) findViewById(R.id.txtJson);
text.setText(s);
progressDialog.dismiss();
}
}
Kindly tell me how to show response of this in listview. Thanks
I'm pulling my hair out trying to get this to work. I'm using OkHTTP to make a POST request to my server. However, every method I've tried of making a successful POST request with parameters, causes the server to go down, giving me a response of '503 service unavailable'. I use exterior clients to test the server, like the Advanced Rest Client extension, and it works perfectly fine.
The URL for the API is in the format of "https://mystuff-herokuapp.com/postuser" and my body parameters are "user_id", "userName", "email". I've tried adding headers to the request, changing from FormBodyEncoding() to MultiPartBuilder(), etc etc.
onCreate
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_dashboard);
//set toolbar as the acting action bar
Toolbar actionToolbar = (Toolbar) findViewById(R.id.toolbar);
setSupportActionBar(actionToolbar);
getSupportActionBar().setDisplayShowTitleEnabled(false);
Intent intent = getIntent();
String photoUrl = intent.getStringExtra("photo");
String userTwitterID = intent.getStringExtra("userID");
String userName = intent.getStringExtra("name");
String userEmail = intent.getStringExtra("email");
JSONObject jObject = new JSONObject();
try {
jObject.put("user_id", userTwitterID);
jObject.put("userName", userName);
jObject.put("userEmail", userEmail);
} catch (JSONException e) {
e.printStackTrace();
}
new UserApiProcess().execute(jObject);
}
Async Task
private class UserApiProcess extends AsyncTask<Object, Void, Void>{
#Override
protected Void doInBackground(Object... strings) {
OkHttpClient client = new OkHttpClient();
RequestBody formBody = new MultipartBuilder()
.addFormDataPart("user_id", "800")
.addFormDataPart("userName", "Nick")
.addFormDataPart("email", "something#something.com")
.build();
Request request = new Request.Builder()
.url("https://mystuff.herokuapp.com/postuser")
.addHeader("Content-Type", "x-www-form-urlencoded")
.post(formBody)
.build();
Response response = null;
try {
response = client.newCall(request).execute();
if(!response.isSuccessful()) throw new IOException("Unexpected code " + response);
System.out.println(response.body().string());
} catch (IOException e) {
e.printStackTrace();
}
return null;
}
}
Successful Response from Advanced Rest Client
My Server Error through Android
Try this. It should work.
private class UserApiProcess extends AsyncTask<Object, Void, Void>{
#Override
protected Void doInBackground(Object... strings) {
OkHttpClient client = new OkHttpClient();
RequestBody formBody = new FormEncodinBuilder()
.add("user_id", "800")
.add("userName", "Nick")
.add("email", "something#something.com")
.build();
Request request = new Request.Builder()
.url("https://mystuff.herokuapp.com/postuser")
.addHeader("Content-Type", "x-www-form-urlencoded")
.post(formBody)
.build();
Response response = null;
try {
response = client.newCall(request).execute();
if(!response.isSuccessful()) throw new IOException("Unexpected code " + response);
System.out.println(response.body().string());
} catch (IOException e) {
e.printStackTrace();
}
return null;
}
}
I am looking for a way how to make a POST (login) https request in android. How to make sure that the code don't trust self-signed/invalid certs. The input to the request needs to be in the following format:
{
"udid": DEVICE_ID
"email": "email#email.com",
"password": "password"
}
I need to make the auth call to this address format:
https://api.ADDRESS.com/v1/auth
Please note that I want to use HTTPs request and not HTTP.
You can use volley/retrofit library for parsing json.
example #
http://www.androidhive.info/2014/05/android-working-with-volley-library-1/
I ended up using OkHTTP after researching if it is secure to use in my case:
public class MainActivity extends AppCompatActivity {
public static final MediaType JSON
= MediaType.parse("application/json; charset=utf-8");
private static final String TAG = MainActivity.class.getSimpleName();
private JSONObject responseJson;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar);
setSupportActionBar(toolbar);
final JSONObject myJson = new JSONObject();
try {
myJson.put("udid","c376e418-da42-39fb-0000-d821f1fd2804");
myJson.put("email","email
myJson.put("password","password");
} catch (JSONException e) {
e.printStackTrace();
}
Thread thread = new Thread(new Runnable(){
#Override
public void run() {
try {
//Your code goes here
String response = post("https://ADDRESS/v1/auth", myJson.toString());
responseJson = new JSONObject(response);
String message = responseJson.getString("message");
String token = responseJson.getString("token");
Log.d(TAG,"Response message: " + message);
Log.d(TAG,"Response token: " + token);
Log.d("MainActivity",response);
} catch (Exception e) {
e.printStackTrace();
}
}
});
thread.start();
}
String post(String url, String json) throws IOException {
OkHttpClient client = new OkHttpClient();
RequestBody body = RequestBody.create(JSON, json);
Request request = new Request.Builder()
.url(url)
.post(body)
.build();
Response response = client.newCall(request).execute();
return response.body().string();
}
}