I am using okhttp library for Json parsing.
I have created my AsyncTask as below for my Login Webservice :
class LoginAsyncTask extends AsyncTask<Void, Void, Void> {
private ProgressDialog dialog;
private String mstrLoginResponse="";
#Override
protected void onPreExecute() {
super.onPreExecute();
try {
dialog = new ProgressDialog(SignInActivity.this);
dialog.requestWindowFeature(Window.FEATURE_NO_TITLE);
dialog.getWindow().setBackgroundDrawable(new ColorDrawable(android.graphics.Color.TRANSPARENT));
dialog.setCancelable(false);
if (!dialog.isShowing()) {
dialog.show();
}
} catch (Exception e) {
e.printStackTrace();
}
}
#Override
protected Void doInBackground(Void... params) {
try {
RequestBody formBody = new FormEncodingBuilder()
.add("mobile_number", strPhone)
.add("password", strPassword)
.build();
mstrLoginResponse = HttpUtils.postRun("login", formBody);
Constant.displayLogE(">>>TT : ",""+mstrLoginResponse);
} catch (Exception e) {
e.printStackTrace();
}
return null;
}
#Override
protected void onPostExecute(Void aVoid) {
super.onPostExecute(aVoid);
if (dialog.isShowing()) {
dialog.dismiss();
}
if (mstrLoginResponse != null) {
try {
JSONObject jsonRegister = new JSONObject(mstrLoginResponse);
int strLoginStatus = jsonRegister.getInt("status");
String strMessage = jsonRegister.getString("message");
if (strLoginStatus == 1) {
JSONObject jsonUserId = jsonRegister.getJSONObject("data");
String strUserId = jsonUserId.getString("user_id");
AppSettings.setPref(SignInActivity.this, USER_ID, String.valueOf(strUserId));
startActivity(new Intent(SignInActivity.this, MainActivity.class));
finish();
Constant.displayToast(SignInActivity.this, "" + strMessage);
} else {
ApiUtils.showAlertDialogue(SignInActivity.this, "" + strMessage);
}
} catch (Exception e) {
e.printStackTrace();
}
}
}
}
But, Unfortunetly getting below response :
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="utf-8">
<title>404 Page Not Found</title>
<style type="text/css">
::selection { background-color: #E13300; color: white; }
::-moz-selection { background-color: #E13300; color: white; }
and Exeption : org.json.JSONException: Value <!DOCTYPE of type java.lang.String cannot be converted to JSONObject
06-24 00:41:03.314 349-349/com.roadysmart W/System.err: at org.json.JSON.typeMismatch(JSON.java:111)
I am getting proper response in Postman.
My HttpUtils class is as below : `
public class HttpUtils {
/*public static final MediaType JSON
= MediaType.parse("application/json; charset=utf-8");*/
public static String BASE_URL = "http://temp.in/projects/temp/";
public static OkHttpClient client = new OkHttpClient();
public static String getRun(String url) throws IOException {
Log.d("URL===>", url);
Request request = new Request.Builder()
.url(url)
.build();
Response response = client.newCall(request).execute();
return response.body().string();
}
public static String postRun(String type, RequestBody formBody) throws IOException {
String str = "";
Request request = new Request.Builder()
.url(BASE_URL)
.post(formBody)
.build();
Response response = client.newCall(request).execute();
return response.body().string();
}
}
What might be the mistake ? Please, Help .
===>>EDIT :
Getting Proper response in postman as below :
{
"status": 1,
"message": "Login successful",
"data": {
"name": "subhu",
"mobile_number": "7777777777",
"email": "bhargavmodi777#gmail.com",
"user_id": "20"
}
}
Your response - <title>404 Page Not Found</title> tells me that your endpoint doesn't exist because you entered it incorrectly or the server is simply not running.
That exception you posted relates to the same issue, it can't parse the JSON because what the web call received was not application/json and instead just raw HTML.
Exeption : org.json.JSONException: Value <!DOCTYPE of type java.lang.String cannot
With that said, public static String BASE_URL = "http://temp.in/projects/temp/"; looks like a bad URL. Here is what I recommend:
First manually load that URL in your browser, you will notice the same HTML your client call received, will be presented to you.
Make sure you are running your server/service or whatever it is that responds to your request. You say Postman works, what parameters did you use? What are you communicating with?
If PostMan works, and postman runs from your computer, your computer is connected to your local network I presume. Is your Android device on the local network as well? Or are you on cell service (3G/LTE). If you are then your endpoint can't be reached unless you are connected to a VPN or something.
Related
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 am using the following code for sending files (pdf,docx,pptx etc) from user to user in a chatting application.
public class UploadFile extends AsyncTask<String, Void, String> {
protected MessageModel mMessage;
File file ;
String mimeType = "";
public UploadFile(MessageModel msg, File file) {
super();
this.mMessage = msg;
this.file = file;
}
#Override
protected void onPreExecute() {
super.onPreExecute();
}
#Override
protected String doInBackground(String... params) {
String responseBodyText = null;
mimeType = mMessage.getMsgFileType();
MediaType MEDIA_TYPE = okhttp3.MediaType.parse(mimeType);
OkHttpClient client = new OkHttpClient();
try {
RequestBody req = new okhttp3.MultipartBody.Builder()
.setType(okhttp3.MultipartBody.FORM)
.addFormDataPart("chatFileUpload", file.getName(), RequestBody.create(MEDIA_TYPE, file)).build();
Request request = new Request.Builder()
.header("Authorization", "Bearer "+Constants.AUTH_TOKEN)
.addHeader("User-Agent", Constants.USER_AGENT)
.url(urlforFileUpload)
.post(req)
.build();
Response response = null;
response = client.newCall(request).execute();
if (!response.isSuccessful()) {
throw new IOException("Okhttp Error: " + response);
} else {
responseBodyText = response.body().string();
Log.d("PrintResponseBody", responseBodyText); // Print the response body here
}
} catch (IOException e) {
e.printStackTrace();
}
return responseBodyText;
}
#Override
protected void onPostExecute(String result) {
super.onPostExecute(result);
JSONObject msgFiles = new JSONObject();
if (result != null) {
try {
JSONObject responseObject = new JSONObject(result);
msgFiles.put("filename", responseObject.get("fileName"));
msgFiles.put("mimetype", responseObject.get("mimetype"));
msgFiles.put("filepath", responseObject.get("fileUploadPath"));
Log.d("PrintFileUploadPath", String.valueOf(responseObject.get("fileUploadPath")));
// Print the response upload file path with file name and extension;
//.... do other stuffs....
} catch (JSONException e) {
e.printStackTrace();
}
}
}
}
In the logcat, I'm getting extension as 'undefined' instead of proper extension name (.docx, .pptx etc). Can someone tell me which might cause this kind of behavior? Is it appropriate? If yes, how am I supposed to check which type of file user is receiving from server response?
An example of response I'm getting using debugger:
{
"status":"true",
"fileName":"1490691261587.undefined",
"fileUploadPath":"/uploads/chat_upload/1490691261587.undefined",
"mimetype":"file/file",
"msg":"File is uploaded successfully",
"downloadLink":"<a target=\"_blank\" href=\"/uploads/chat_upload/1490691261587.undefined\">New-Text-Document.txt909.txt</a>"
}
Thanks in advance.
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.
The api my app is working with is expecting a GET request for search results that looks like this:
Method: GET
Headers:
{
"Content-Type": "application/json",
"X-AUTHORIZATION": "8eb40dba2f0c6d7de8b9c6e1865aa507"
}
Request:
{
"keyword": "X S"
}
Response:
{
"status": "success",
"code": 0,
"meta": {
"exec_time": 0.012183904647827
},
"message": "",
"data": [
]
}
I have a class called HttpGetWithEntity that i found online that looks like this:
public class HttpGetWithEntity extends HttpEntityEnclosingRequestBase {
public HttpGetWithEntity() {
super();
}
public HttpGetWithEntity(URI uri) {
super();
setURI(uri);
}
public HttpGetWithEntity(String uri) {
super();
setURI(URI.create(uri));
}
#Override
public String getMethod() {
return HttpGet.METHOD_NAME;
}
}
and i am implementing it like so:
public HttpResponse invokeXAUTHGETJsonService(String url, String token,
String jsonPost) {
Log.v("KEYWORD", "KEYWORD GOING UP:"+jsonPost);
HttpParams params = new BasicHttpParams();
HttpResponse response = null;
try {
HttpGetWithEntity request = new HttpGetWithEntity(url);
Log.v("UPU", "URL:" + url +" token:"+token);
request.setHeader("X-AUTHORIZATION", token);
request.setHeader("Accept", "application/json");
request.addHeader("Content-Type", "application/json");
StringEntity se = new StringEntity(jsonPost);
request.setEntity(se);
response = client.execute(request);
} catch (ClientProtocolException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
return response;
}
My log to check the json i am posting looks like this:
03-09 14:38:01.034: V/KEYWORD(11739): KEYWORD CREATED: {"keyword":"e"}
The problem is, it seems like the JSON never reaches the api or is ignored. Does anyone know what i am doing wrong..
thanks
GET method will not send the request.entity to the server..
instead of using "request.setEntity() .."
just access the parms of the request setting " "keyword": "X S"" as parm K-V pair and append them to the url that you are GETTING:
domain/path?keyword=X%20S
do not use the entity unless you are POST or PUT method.
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();
}
}