Issue
I use AsyncTask and GET Method to send variable to server and get JSON object back and parse the JSON Object, it works!
But now, I want to change my method that use POST method to send variable to server and get JSON object back and parse the JSON Object, not to use GET method.
What can I do?
Here is my code that use GET Method to send variable to server and get JSON object and parse the JSON Object:
public class MainActivity extends AppCompatActivity {
public static String TAG = "MainActivity";
public static String deviceIMEI;
public static String token;
TelephonyManager telephonyManager;
public static String memoryToken;
public static SharedPreferences setting;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
memoryToken = null;
deviceId();
if (ActivityCompat.checkSelfPermission(this, Manifest.permission.READ_PHONE_STATE) != PackageManager.PERMISSION_GRANTED) {
// TODO: Consider calling
// ActivityCompat#requestPermissions
// here to request the missing permissions, and then overriding
// public void onRequestPermissionsResult(int requestCode, String[] permissions,
// int[] grantResults)
// to handle the case where the user grants the permission. See the documentation
// for ActivityCompat#requestPermissions for more details.
return;
}
deviceIMEI = telephonyManager.getDeviceId();
if(deviceIMEI != null){
setting = getSharedPreferences("UserData", MODE_PRIVATE);
memoryToken = setting.getString("Token", "");
if(memoryToken != null && memoryToken != ""){
Intent i = new Intent(MainActivity.this, CoverActivity.class);
startActivity(i);
}
else if(memoryToken == ""){
new JSONTask().execute("api1" + "?deviceId=" + deviceIMEI + "&os=0");
Intent i = new Intent(MainActivity.this, CoverActivity.class);
startActivity(i);
}
else{
}
}
else{
}
}
private void deviceId() {
telephonyManager = (TelephonyManager) getSystemService(this.TELEPHONY_SERVICE);
if (ActivityCompat.checkSelfPermission(this, Manifest.permission.READ_PHONE_STATE) != PackageManager.PERMISSION_GRANTED) {
ActivityCompat.requestPermissions(this, new String[]{Manifest.permission.READ_PHONE_STATE}, 1);
return;
}
}
@Override
public void onRequestPermissionsResult(int requestCode, String[] permissions, int[] grantResults){
switch (requestCode) {
case 1:
if (grantResults[0] == PackageManager.PERMISSION_GRANTED) {
if (ActivityCompat.checkSelfPermission(this, Manifest.permission.READ_PHONE_STATE) != PackageManager.PERMISSION_GRANTED) {
ActivityCompat.requestPermissions(this, new String[]{Manifest.permission.READ_PHONE_STATE}, 1);
return;
}
String iemi = telephonyManager.getDeviceId();
deviceIMEI = iemi;
if(deviceIMEI != null){
new JSONTask().execute("api1" + "?deviceId=" + deviceIMEI + "&os=0");
Intent i = new Intent(MainActivity.this, CoverActivity.class);
startActivity(i);
}
} else {
}
break;
default:
super.onRequestPermissionsResult(requestCode, permissions, grantResults);
}
}
public class JSONTask extends AsyncTask<String, String, String> {
@Override
protected String doInBackground(String... params) {
HttpURLConnection connection = null;
BufferedReader reader = null;
try {
URL url = new URL(params[0]);
connection = (HttpURLConnection) url.openConnection();
connection.connect();
InputStream stream = connection.getInputStream();
reader = new BufferedReader(new InputStreamReader(stream));
StringBuffer buffer = new StringBuffer();
String line = "";
while ((line = reader.readLine()) != null) {
buffer.append(line);
}
String finalJson = buffer.toString();
try{
JSONObject jsonObject = new JSONObject(finalJson);
String code = jsonObject.getString("code");
String desc = jsonObject.getString("desc");
if(Integer.valueOf(code) == 1){
JSONObject userInfo = jsonObject.getJSONObject("userInfo");
token = userInfo.getString("token");
Log.e(TAG, "token in JSONTask : " + token);
setting = getSharedPreferences("UserData", MODE_PRIVATE);
setting.edit().clear().commit();
setting.edit().putString("Token", token).commit();
memoryToken = setting.getString("Token", "");
}
else{
}
} catch (JSONException e) {
e.printStackTrace();
}
//return buffer.toString();
} catch (MalformedURLException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
} finally {
if (connection != null) {
connection.disconnect();
}
try {
if (reader != null) {
reader.close();
}
} catch (IOException e) {
e.printStackTrace();
}
}
return null;
}
@Override
protected void onPostExecute(String result) {
super.onPostExecute(result);
}
}
}
Solution
If you want to send your data using post in HttpUrlConnection then you need to write that data in your body.
I have created one class and i have added both methods for GET
and POST
in single file. You just need to call this method with your URL
and Parameters
for Api Call.
Please check this file: https://filebin.net/rwg3i8mdpt77rju4/ApiCall.java?t=68ibdati
if you see in the attached ApiCall.java
file, there is two methods. ApiCall.getWebserviceCall()
and ApiCall.postWebserviceCall()
will return you Api response in string format. Then you can perform your JSON Parsing code.
You can call POST and GET methods by using below way. And as per your AsyncTask, you can use this methods like,
public class JSONTask extends AsyncTask<String, String, String> {
private Context context;
private String deviceIMEI;
private String os;
public JSONTask(Context context, String deviceIMEI, String os) {
this.context = context;
this.deviceIMEI = deviceIMEI;
this.os = os;
}
@Override
protected String doInBackground(String... params) {
try {
String SERVER_WS_URL = params[0];
LinkedHashMap<String, String> parameter = new LinkedHashMap<>();
parameter.put("deviceId", deviceIMEI);
parameter.put("os", "0");
return ApiCall.postWebserviceCall(SERVER_WS_URL, params);
// return ApiCall.getWebserviceCall(SERVER_WS_URL, params); // If you want to call GET Api
} catch (Exception e) {
return null;
}
}
@Override
protected void onPostExecute(String result) {
super.onPostExecute(result);
try {
if (result != null) {
JSONObject jsonObject = new JSONObject(result.toString());
String code = jsonObject.getString("code");
String desc = jsonObject.getString("desc");
if (Integer.valueOf(code) == 1) {
JSONObject userInfo = jsonObject.getJSONObject("userInfo");
token = userInfo.getString("token");
Log.e(TAG, "token in JSONTask : " + token);
setting = getSharedPreferences("UserData", MODE_PRIVATE);
setting.edit().clear().commit();
setting.edit().putString("Token", token).commit();
memoryToken = setting.getString("Token", "");
} else {
}
} else {
Toast.makeText(context, "Something went wrong", Toast.LENGTH_SHORT).show();
}
} catch (JSONException e) {
e.printStackTrace();
}
}
}
Now you can call this AsyncTask using
new JSONTask(deviceIMEI, "0").execute("api1");
Answered By - Ajay Mehta
0 comments:
Post a Comment
Note: Only a member of this blog may post a comment.