Android reads different data in JsonArray on receiving from server - java

I'm working on an API and I am experiencing a strange thing. When I make an API request from which I receive a JSON response. In the browser I receive the following JSON:
[
{
"SalesAgentPhone":"829698539",
"DriverStatus":"CustomerRescheduled",
"DriverStatusDescription":[
{
"Reason":"sfdfsdf",
"Date":"2016-10-02",
"SlotId":"1"
}
]
}]
But I receive a different JSON response on my Android device.
[
{
"SalesAgentPhone":"829698539",
"DriverStatus":"CustomerRescheduled",
"DriverStatusDescription":[
{"Reason":"sfdfsdf","Date":"2016-10-02","SlotId":"1"
}
]
}]
This is the class I'm using to make that Request
public class NewPost extends AsyncTask<String, Integer, String> {
private final Context context;
private final Registerinterface inter;
private int response_code = 0;
private HashMap<String, String> postDataParams;
private ProgressDialog prgDialog;
public NewPost(Context c, Registerinterface inter, HashMap<String, String> postParamater) {
context = c;
this.inter = inter;
this.postDataParams = postParamater;
}
#Override
protected void onPreExecute() {
super.onPreExecute();
if (!new NetworkStatus(context).isNetworkAvailable()) {
inter.Result("", Constants.No_Internet);
this.cancel(true);
} else {
prgDialog = new ProgressDialog(new ContextThemeWrapper(context, android.R.style.Theme_DeviceDefault_Light_Dialog));
prgDialog.setMessage("Loading...");
prgDialog.show();
prgDialog.setIndeterminate(false);
}
}
#Override
protected String doInBackground(String... param) {
URL url;
String response = "";
try {
url = new URL(param[0]);
HttpURLConnection conn = (HttpURLConnection) url.openConnection();
conn.setReadTimeout(15000);
conn.setConnectTimeout(15000);
conn.setRequestMethod("GET");
conn.setDoInput(true);
conn.setDoOutput(true);
OutputStream os = conn.getOutputStream();
BufferedWriter writer = new BufferedWriter(
new OutputStreamWriter(os, "UTF-8"));
writer.write(getPostDataString(postDataParams));
writer.flush();
writer.close();
os.close();
int responseCode = conn.getResponseCode();
if (responseCode == HttpsURLConnection.HTTP_OK) {
String line;
StringBuilder sb = new StringBuilder();
BufferedReader br = new BufferedReader(new InputStreamReader(conn.getInputStream()));
while ((line = br.readLine()) != null)
sb.append(line + "\n");
response = sb.toString();
return response;
} else {
response = "";
}
} catch (Exception e) {
e.printStackTrace();
}
return response;
}
#Override
protected void onPostExecute(String result) {
super.onPostExecute(result);
prgDialog.dismiss();
if (result == null || result.equals("null"))
inter.Result("null", response_code);
else
inter.Result(result, response_code);
}
private String getPostDataString(HashMap<String, String> params) throws UnsupportedEncodingException {
StringBuilder result = new StringBuilder();
boolean first = true;
for (Map.Entry<String, String> entry : params.entrySet()) {
if (first)
first = false;
else
result.append("&");
result.append(URLEncoder.encode(entry.getKey(), "UTF-8"));
result.append("=");
result.append(URLEncoder.encode(entry.getValue(), "UTF-8"));
}
return result.toString();
}
}
I've been stuck on this problem for hours, any help would be appreciated.

You can remove the from your JSON data.
JSON.parse(data.replace(/"/g,'"'));
You might want to fix your JSON-writing script though, because " is not valid in a JSON object.

Related

creating custom onError and onLoad Methods in Java

I have been working on my own Http Client Class, and i want a way to implement the onload and oerror feature like, "declaring an event and actions for that event", if an error with the connection happened i must have the ability to specify a custom action for it.
public static void Error(int code){
System.out.println("Oops, something went wrong Error code:" + code.toString());
}
URL url = new URL("http://example.com/");
Map<String, String> params = new HashMap<String, String>();
params.put("key","value");
http_client client = new http_client(url, "GET", params , true);
client.onError = Error(client.ErrorCode);
Something like that.
Here is my class:
class http_client {
protected String responseText;
protected boolean loaded = false;
protected boolean error = false;
public http_client(URL url, String method , Map<String,String> parameters , boolean cache) throws IOException, ProtocolException{
HttpURLConnection connection = (HttpURLConnection) url.openConnection();
int status = connection.getResponseCode();
if(status > 299){
error = true;
}
connection.setRequestMethod(method);
if(method == "POST"){
connection.setRequestProperty("Content-Type", "application/x-www-form-urlencoded");
}
connection.setUseCaches(cache);
connection.setDoInput(true);
connection.setDoOutput(true);
DataOutputStream s = new DataOutputStream(connection.getOutputStream());
s.writeBytes(paramToStr(parameters));
s.flush();
s.close();
InputStream is = connection.getInputStream();
BufferedReader reader = new BufferedReader(new InputStreamReader(is));
StringBuilder response = new StringBuilder();
String CurrentLine;
int lines = 0;
while((CurrentLine = reader.readLine()) != null){
lines += 1;
response.append(CurrentLine + "\n");
}
reader.close();
responseText = response.toString();
responseText = responseText.substring(0 , responseText.length() - 1);
if(lines == 1){
responseText = responseText.replace("\n","");
}
loaded = true;
}
public static String paramToStr(Map<String, String> parameters) throws UnsupportedEncodingException{
StringBuilder result = new StringBuilder();
result.append("?");
for(Map.Entry<String,String> entry: parameters.entrySet()){
String key = URLEncoder.encode(entry.getKey() , "UTF-8");
String value = URLEncoder.encode(entry.getValue() , "UTF-8");
result.append(key);
result.append("=");
result.append(value);
result.append("&");
}
String str = result.toString();
str = result.substring(0 , str.length() - 1);
return str;
}
}
Thanks in advance.
You can use the Function Interface Java provides:
class http_client {
protected String responseText;
protected boolean loaded = false;
protected Function<Integer, Void> success;
protected Function<Integer, Void> error;
public http_client(URL url, String method , Map<String,String> parameters , boolean cache, Function<Integer, String>success, Function<Integer, String> error) throws IOException, ProtocolException{
HttpURLConnection connection = (HttpURLConnection) url.openConnection();
int status = connection.getResponseCode();
if(status > 299){
error.apply(status);
} else {
success.apply(status);
}
...
}
}
to call it just pass some lambda function
...
http_client client = new http_client(url, "GET", params , true, status -> System.out.println("success! " + status), status -> System.out.println("error " + status));

How can I solve this IOException?

I am trying to get a user token from a url but I keep getting an IOException:
(W/System.err: java.io.FileNotFoundException: url)
I have tried to run the API from postman, and that seems to work. The request method is GET:
private class userlogin extends AsyncTask<String, String, String> {
#Override
public void onPreExecute() {
progressDialog = new ProgressDialog(userLogin.this);
progressDialog.setMessage("please wait.........");
progressDialog.setIndeterminate(false);
progressDialog.setCancelable(false);
progressDialog.setTitle("Logging in");
progressDialog.show();
}
#Override
public String doInBackground(String... para) {
try {
URL url = new URL(webconfigs.LOGIN_URL);
Map<String, String> params = new LinkedHashMap<>();
params.put("grant_type", "password");
params.put("username", para[0]);
params.put("password", para[1]);
utility.updateSharedPreference(userLogin.this, "Username", para[0]);
utility.updateSharedPreference(getApplicationContext(), "Password", para[1]);
//just to check if it is sored in the shared prefrence
utility.fetchFromSharedPreference(getApplicationContext(), "Username");
utility.fetchFromSharedPreference(getApplicationContext(), "Password");
Log.e(">>Username>>", para[0]);
Log.e(">>Password>>", para[1]);
StringBuilder postData = new StringBuilder();
for (Map.Entry<String, String> param : params.entrySet()) {
if (postData.length() != 0) postData.append('&');
postData.append(URLEncoder.encode(param.getKey(), "UTF-8"));
postData.append('=');
postData.append(URLEncoder.encode(String.valueOf(param.getValue()), "UTF-8"));
}
String urlparameters = postData.toString();
HttpURLConnection conn = (HttpURLConnection) url.openConnection();
conn.setConnectTimeout(3000);
conn.setRequestMethod("GET");
conn.setRequestProperty("Content-Type", webconfigs.CONTENT_TYPE);
conn.setDoOutput(true);
//connect the url
conn.connect();
//conn.setDoOutput(true);
OutputStreamWriter writer = new OutputStreamWriter(conn.getOutputStream());
writer.write(urlparameters);
writer.flush();
//create our buffered reader to read from the input stream reader
BufferedReader reader = new BufferedReader(new InputStreamReader(conn.getInputStream()));
StringBuilder st = new StringBuilder();
//checking the status of the response code
Integer resposeCode = conn.getResponseCode();
String responsecode1 = resposeCode.toString();
Log.e("the respose code is :", responsecode1);
String line;
String result= "";
// consume the response and read it line by line as
while ((line = reader.readLine()) != null) {
st.append(line);
}
reader.close();
writer.close();
result = st.toString();
return result;
} catch (Exception e) {
e.printStackTrace();
}
return null;
}
#Override
protected void onPostExecute(String result) {
super.onPostExecute(result);
Log.e(">>>>LOGINSERVERRESPONSE", ">>>>>" + result);
progressDialog.dismiss();
try {
JSONObject results = new JSONObject(result);
String token = results.getString("access_token");
if (token != null) {
String accessToken = results.getString("access_token");
String tokenType = results.getString("token_type");
String dateIssued = results.getString(".issued");
String expiryDate = results.getString(".expires_in");
}
} catch (Exception e) {
}
startActivity(new Intent(getApplicationContext(), drawerLayout.class));
}
}
the problem with using the asynchtask is that when the credentials that are used are wrong the problem will exist ,incase that happens,use a different user from the database

Post request on Android to .php file

I'm trying to make a POST request from my android app to a .php file but it doesn't work. It should send the scannedData value to my .php script but instead it returns "false: 500".
Does anybody know why? Since they changed that you can't use httppost anymore most of the answers on StackOverflow are outdated.
public class SendRequest extends AsyncTask<String, Void, String> {
protected void onPreExecute(){}
protected String doInBackground(String... arg0) {
try{
//Enter script URL Here
URL url = new URL("https://example.com/code.php");
JSONObject postDataParams = new JSONObject();
//int i;
//for(i=1;i<=70;i++)
// String usn = Integer.toString(i);
//Passing scanned code as parameter
postDataParams.put("sdata",scannedData);
Log.e("params",postDataParams.toString());
HttpURLConnection conn = (HttpURLConnection) url.openConnection();
conn.setReadTimeout(15000 /* milliseconds */);
conn.setConnectTimeout(15000 /* milliseconds */);
conn.setRequestMethod("POST");
conn.setDoInput(true);
conn.setDoOutput(true);
OutputStream os = conn.getOutputStream();
BufferedWriter writer = new BufferedWriter(
new OutputStreamWriter(os, "UTF-8"));
writer.write(getPostDataString(postDataParams));
writer.flush();
writer.close();
os.close();
int responseCode=conn.getResponseCode();
if (responseCode == HttpsURLConnection.HTTP_OK) {
BufferedReader in=new BufferedReader(new InputStreamReader(conn.getInputStream()));
StringBuffer sb = new StringBuffer("");
String line="";
while((line = in.readLine()) != null) {
sb.append(line);
break;
}
in.close();
return sb.toString();
}
else {
return new String("false : "+responseCode);
}
}
catch(Exception e){
return new String("Exception: " + e.getMessage());
}
}
#Override
protected void onPostExecute(String result) {
Toast.makeText(getApplicationContext(), result,
Toast.LENGTH_LONG).show();
}
}
public String getPostDataString(JSONObject params) throws Exception {
StringBuilder result = new StringBuilder();
boolean first = true;
Iterator<String> itr = params.keys();
while(itr.hasNext()){
String key= itr.next();
Object value = params.get(key);
if (first)
first = false;
else
result.append("&");
result.append(URLEncoder.encode(key, "UTF-8"));
result.append("=");
result.append(URLEncoder.encode(value.toString(), "UTF-8"));
}
return result.toString();
}

Android: java.net.ProtocolException: Unexpected status line: HTTP/1.2 200 OK

I have been working on the following code for a while.
the code worked for the 5.x version of my app but I can't get the code to work for Android version 6.x and higher.
public class PostAsync extends AsyncTask<String, Integer, Double> {
private Context _context = null;
public PostAsync(Context context) {
_context = context;
}
#Override
protected Double doInBackground(String... params) {
String serverResponse = postData(params[0]);
try {
JSONObject obj = new JSONObject(serverResponse);
String id = "";
JSONObject locationobj = obj.getJSONObject("X");
JSONObject response = locationobj.getJSONObject("Y");
id = response.getString("id");
Settings.idcode = id;
// Convert , to %2c, since we're working with a URI here
String number = Settings.number + Settings.code + "," + Settings.idcode; // %2c
_context.startActivity(new Intent(Intent.ACTION_CALL).setData(Uri.parse("tel://" + number)));
}
catch (Exception e) {
// TODO: Errorhandler
e.printStackTrace();
}
return null;
}
protected void onPostExecute(Double result) {
}
protected void onProgressUpdate(Integer... progress) {
}
// Send a POST request to specified url in Settings class, with defined JSONObject message
public String postData(String msg) {
String result = null;
StringBuffer sb = new StringBuffer();
InputStream is = null;
try {
URL url = new URL(Settings.webURL);
HttpURLConnection connection = (HttpURLConnection) url.openConnection();
connection.setDoOutput(true);
connection.setDoInput(true);
connection.setChunkedStreamingMode(0);
connection.setReadTimeout(15000);
connection.setConnectTimeout(15000);
connection.setRequestProperty("Content-Encoding", "identity");
connection.setRequestProperty("Accept-Encoding", "identity");
connection.setRequestProperty("User-Agent", "Mozilla/5.0");
connection.setRequestProperty("TYPE", "JSON");
connection.setRequestProperty("KEY", "key");
DataOutputStream wr = new DataOutputStream(connection.getOutputStream());
wr.writeBytes(msg);
wr.flush();
wr.close();
int responseCode = connection.getResponseCode();
String responseMessage = connection.getResponseMessage();
System.out.println("Response code: " + responseCode);
System.out.println("Response message: " + responseMessage);
if(responseCode == HttpURLConnection.HTTP_OK){
is = new BufferedInputStream(connection.getInputStream());
BufferedReader br = new BufferedReader(new InputStreamReader(is));
String inputLine = "";
try {
while ((inputLine = br.readLine()) != null) {
sb.append(inputLine);
}
result = sb.toString();
} catch (IOException e) {
e.printStackTrace();
} finally {
if (is != null) {
try {
is.close();
}
catch (IOException e) {
e.printStackTrace();
}
}
}
}
} catch (IOException e) {
e.printStackTrace();
}
return result;
}
}
I get the following error
java.net.ProtocolException: Unexpected status line: HTTP/1.2 200 OK
Can someone tell me what I am missing?

POST data not sent via HttpURLConnection

I'm trying to send POST request via HttpURLConnection, here is the code
public class BackgroundTask extends AsyncTask<String, Void, Void> {
Context context;
Activity activity;
StringBuffer str = null;
int responseCode;
String responseMessage;
public BackgroundTask(Context context) {
this.context = context;
this.activity = (Activity) context;
}
#Override
protected Void doInBackground(String... params) {
HttpURLConnection connection = null;
OutputStream outputStream = null;
InputStream inputStream = null;
BufferedReader reader = null;
BufferedWriter writer = null;
String method = params[1];
if(method.equals("post")) {
try {
URL url = new URL(params[0]);
connection = (HttpURLConnection) url.openConnection();
connection.setDoOutput(true);
connection.setRequestMethod("POST");
connection.setRequestProperty("Content-Type", "application/x-www-form-urlencoded");
outputStream = connection.getOutputStream();
writer = new BufferedWriter(new OutputStreamWriter(outputStream, "UTF-8"));
String data = URLEncoder.encode(params[2] + "=" + params[3], "UTF-8");
writer.write(data);
responseCode = connection.getResponseCode();
responseMessage = connection.getResponseMessage();
inputStream = connection.getInputStream();
reader = new BufferedReader(new InputStreamReader(inputStream));
str = new StringBuffer();
String line = "";
while ((line = reader.readLine()) != null) {
str.append(line);
}
} catch (MalformedURLException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
} finally {
if (connection != null)
connection.disconnect();
if (reader != null) {
try {
reader.close();
} catch (IOException e) {
e.printStackTrace();
}
}
if (writer != null) {
try {
writer.flush();
writer.close();
} catch (IOException e) {
e.printStackTrace();
}
}
if (inputStream != null) {
try {
inputStream.close();
} catch (IOException e) {
e.printStackTrace();
}
}
if (outputStream != null) {
try {
outputStream.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
} else if(method.equals("get")) {
}
return null;
}
#Override
protected void onProgressUpdate(Void... values) {
super.onProgressUpdate(values);
}
#Override
protected void onPostExecute(Void aVoid) {
TextView txt = (TextView) activity.findViewById(R.id.txt);
if(str != null)
txt.setText(str.toString());
Toast.makeText(activity, responseMessage, Toast.LENGTH_LONG).show();
}
}
responseCode is 200 which means everything went OK, however it says Undefined index: id
id is well defined inside php file
$user = User::find_by_id($_POST['id']);
echo json_encode($user);
and it works fine when I send post request from an html file yet when i send it from application it says id undefined which means that POST data is not sent.
btn.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
BackgroundTask myTask = new BackgroundTask(MainActivity.this);
myTask.execute(link, "post", "id", "5");
}
});
this is how i instantiate asynctask object inside main activity
UPDATE: when i send not encoded string it works fine!
writer.write("id=5"); // works perfectly!
what is wrong with URLEncoder i use in the code?
I believe you have a problem in this line:
String data = URLEncoder.encode(params[2] + "=" + params[3], "UTF-8");
You are url-encoding the = as well as the params, that's why the server cannot recognise the form fields. Try to encode the params only:
String data = URLEncoder.encode(params[2], "UTF-8") + "=" + URLEncoder.encode(params[3], "UTF-8");
The reason is that URL encoding is for passing special characters like = in the value(or key). Basically, the server will split and parse the key-value pairs with & and = before doing the decoding. And when you url-encode the = character, the server simply couldn't recognise it during the split and parse phase.
When i need to communicate with the server i use this
Server Class
public static String sendPostRequest(String requestURL,
HashMap<String, String> postDataParams) {
URL url;
String response = "";
try {
url = new URL(requestURL);
HttpURLConnection conn = (HttpURLConnection) url.openConnection();
conn.setReadTimeout(15000);
conn.setConnectTimeout(15000);
conn.setRequestMethod("POST");
conn.setDoInput(true);
conn.setDoOutput(true);
OutputStream os = conn.getOutputStream();
BufferedWriter writer = new BufferedWriter(
new OutputStreamWriter(os, "UTF-8"));
writer.write(getPostDataString(postDataParams));
writer.flush();
writer.close();
os.close();
int responseCode = conn.getResponseCode();
if (responseCode == HttpsURLConnection.HTTP_OK) {
BufferedReader br = new BufferedReader(new InputStreamReader(conn.getInputStream()));
response = br.readLine();
} else {
response = "Error Registering";
}
} catch (Exception e) {
e.printStackTrace();
}
return response;
}
private static String getPostDataString(HashMap<String, String> params) throws UnsupportedEncodingException {
StringBuilder result = new StringBuilder();
boolean first = true;
for (Map.Entry<String, String> entry : params.entrySet()) {
if (first)
first = false;
else
result.append("&");
result.append(URLEncoder.encode(entry.getKey(), "UTF-8"));
result.append("=");
result.append(URLEncoder.encode(entry.getValue(), "UTF-8"));
}
return result.toString();
}
OtherClass
//Run this inside an Asynctask
HashMap<String,String> data = new HashMap<>();
data.put("id", id);
String serverResponce = Server.sendPostRequest(URL,data);

Categories

Resources