I am returning a JSON string from PHP:
<?php
$results = array(
"result" => "success",
"username" => "some username",
"projects" => "some other value"
);
echo json_encode($results);
?>
I found a java example online that works. It uses StringBuilder and outputs the response using Toast. I want to actually parse it as a JSON object so I can reference each key=>value, but not sure how to do it. This is the example I am using:
private void tryLogin(String usernameInput, String passwordInput)
{
HttpURLConnection connection;
OutputStreamWriter request = null;
URL url = null;
String response = null;
String parameters = "username=" + usernameInput + "&password=" + passwordInput;
try
{
url = new URL(getString(R.string.loginLocation));
connection = (HttpURLConnection) url.openConnection();
connection.setDoOutput(true);
connection.setRequestProperty("Content-Type", "application/x-www-form-urlencoded");
connection.setRequestMethod("POST");
request = new OutputStreamWriter(connection.getOutputStream());
request.write(parameters);
request.flush();
request.close();
String line = "";
InputStreamReader isr = new InputStreamReader(connection.getInputStream());
BufferedReader reader = new BufferedReader(isr);
StringBuilder sb = new StringBuilder();
while ((line = reader.readLine()) != null)
{
sb.append(line + "\n");
}
response = sb.toString();
Toast.makeText(this, "Message from server: \n" + response, 0).show();
isr.close();
reader.close();
}
catch(IOException e)
{
Log.i("NetworkTest","Network Error: " + e);
}
}
This is what the code currently returns:
05-04 19:19:54.724: INFO/NetworkTest(1061): {"result":"success","username":"rondog","projects":"1,2"}
Just to be clear, I am pretty sure I know how to parse the string. What I am confused on is getting the response back from the server and pushing that to the JSONObject (or is 'response' the object that I pass?). Any help is appreciated, thanks!
(or is 'response' the object that I pass?)
Yes, it is. It expects a string object in it's constructor to parse it.
Related
I have a method in Java where I try to get one integer (user id) through a POST json request, this is the method:
public static Integer getUserIdOwnerOfMsg(Message msg) {
Integer idUser = null;
try {
JSONObject jsonObject = new JSONObject();
jsonObject.put("textMsg", msg.getTextMsg());
jsonObject.put("hourMsg", msg.getHourMsg());
List list = new LinkedList();
list.addAll(Arrays.asList(jsonObject));
String jsonString = list.toString();
String urlStr = SERVER_PATH + "getUserIdOwnerOfMsgJSON.php";
URL url = new URL(urlStr);
HttpURLConnection con = (HttpURLConnection) url.openConnection();
con.setRequestMethod("POST");
con.setRequestProperty("User-Agent", "your user agent");
con.setRequestProperty("Accept-Language", "sp,SP;q=0.5");
//con.setRequestProperty("Content-Type", "text/html; charset=UTF-8");
String urlParameters = "json=" + jsonString;
con.setDoOutput(true);
DataOutputStream wr = new DataOutputStream(con.getOutputStream());
wr.writeBytes(urlParameters);
wr.flush();
wr.close();
InputStream instream;
int status = con.getResponseCode();
if (status != HttpURLConnection.HTTP_OK)
instream = con.getErrorStream();
else
instream = con.getInputStream();
BufferedReader in = new BufferedReader(new InputStreamReader(instream, "UTF-8")); // ISO-8859-1
in.mark(1);
if(in.read() != 0xFEFF)
in.reset();
String inputLine;
StringBuilder response = new StringBuilder();
while((inputLine = in.readLine()) != null)
response.append(inputLine);
in.close();
JSONObject object = new JSONObject(response.toString());
Boolean correct = object.getBoolean("correct");
if (correct) {
idUser = object.getInt("id");
}
} catch (Exception e) {
e.printStackTrace();
}
return idUser;
}
The problem is that the response contains a UTF-8 BOM character, on postman the result it's ok and I can see the id: ({"id":"7","correct":true})
But debugging on android studio I got the value "" or null for idUser, I don't know why, I've tried so many ways to resolve this problem without succeed.
Also on the php server side I've executed echo mb_detect_encoding($idUsuario); and I got ASCII encoding in case that could help to find the solution.
Any help will be apreciated, thank you!
So finally I got the solution, I post it here in case someone have the same issue as me, the problem was with the parameters of the JSON, because they included UTF-8 characters like €, so instead of reading the parameters like this:
wr.writeBytes (urlParameters);
I have to do this:
byte[] buf = urlParameters.getBytes("UTF-8");
wr.write(buf, 0, buf.length);
I post also the complete function in case someone needs it:
public static Integer getUserIdOwnerOfMsg(Message msg) {
Integer idUser = null;
try {
JSONObject jsonObject = new JSONObject();
jsonObject.put("textMsg", msg.getTextMsg());
jsonObject.put("hourMsg", msg.getHourMsg());
List list = new LinkedList();
list.addAll(Arrays.asList(jsonObject));
String jsonString = list.toString();
String urlStr = SERVER_PATH + "getUserIdOwnerOfMsgJSON.php";
URL url = new URL(urlStr);
HttpURLConnection con = (HttpURLConnection) url.openConnection();
con.setRequestMethod("POST");
con.setRequestProperty("User-Agent", "your user agent");
con.setRequestProperty("Accept-Language", "sp,SP;q=0.5");
String urlParameters = "json=" + jsonString;
con.setDoOutput(true);
DataOutputStream wr = new DataOutputStream (con.getOutputStream());
byte[] buf = urlParameters.getBytes("UTF-8");
wr.write(buf, 0, buf.length);
wr.flush();
wr.close();
InputStream instream;
int status = con.getResponseCode();
if (status != HttpURLConnection.HTTP_OK)
instream = con.getErrorStream();
else
instream = con.getInputStream();
BufferedReader in = new BufferedReader(new InputStreamReader(instream, Charset.forName("UTF-8")),8192);
String inputLine;
StringBuilder response = new StringBuilder();
while((inputLine = in.readLine()) != null)
response.append(inputLine);
JSONObject object = new JSONObject(response.toString());
Boolean correct = object.getBoolean("correct");
if (correct) {
try {
String idUserText = object.getString("id");
idUser = Integer.valueOf(idUserText);
} catch (NumberFormatException e) {
e.printStackTrace();
}
}
in.close();
} catch (Exception e) {
e.printStackTrace();
}
return idUser;
}
That's all, happy coding!
I m trying to send a Json Post request using my Android Application.
But something weird happens.
Here is my Android Code:
try {
URL url = new URL(BASE_URL + params[0]);
HttpURLConnection connection = (HttpURLConnection) url.openConnection();
connection.setRequestMethod("POST");
connection.setDoOutput(true);
connection.setRequestProperty("Content-Type","application/json");
connection.connect();
//JSonObject
JSONObject json = new JSONObject();
for(int i = 0 ; i < jsonValues.size(); i +=2){
json.put(jsonValues.get(i), jsonValues.get(i + 1));
}
jsonValues.clear();
DataOutputStream output = new DataOutputStream(connection.getOutputStream());
//String encoded= URLEncoder.encode(json.toString(),"UTF-8");
output.writeBytes(URLEncoder.encode(json.toString(),"UTF-8"));
output.flush();
output.close();
int HttpResult = connection.getResponseCode();
if(HttpResult ==HttpURLConnection.HTTP_OK){
BufferedReader br = new BufferedReader(new InputStreamReader(
connection.getInputStream(),"UTF-8"));
String line = null;
StringBuilder sb = new StringBuilder();
while ((line = br.readLine()) != null) {
String lineDecoded = URLDecoder.decode(line, "UTF-8");
sb.append(lineDecoded + "\n");
}
br.close();
System.out.println(""+sb.toString());
if(sb != null){
return sb.toString();
}else{
return null;
}
}else{
Log.d("ERRORRRRR",connection.getResponseMessage());
return connection.getResponseMessage();
}
} catch (MalformedURLException e) {
e.printStackTrace();
return e.toString();
} catch (IOException e) {
e.printStackTrace();
return e.toString();
} catch (JSONException e) {
e.printStackTrace();
return e.toString();
}
My php code is this:
$content = file_get_contents("php://input");
if(strcasecmp($_SERVER['REQUEST_METHOD'], 'POST') != 0)
{
throw new Exception('Request method must be POST!');
}
//Make sure that the content type of the POST request has been set to
application/json
$contentType = isset($_SERVER["CONTENT_TYPE"]) ? trim($_SERVER["CONTENT_TYPE"]) : '';
if(strcasecmp($contentType, 'application/json') != 0){
throw new Exception('Content type must be: application/json');
}
//Receive the RAW post data.
$content = trim(file_get_contents("php://input"));
//Attempt to decode the incoming RAW post data from JSON.
$decoded = json_decode($content, true);
echo($decoded);
exit;
The $decoded is null when I make a request using my Android application and using json_last_error() function I get JSON_ERROR_SYNTAX.
This is the raw content of the post request:
{"name":"test","identifier":"12345677"}
But I can't understand what is the problem. In fact when I try to use Advance Rest Client to simulate the same request it works perfectly as shown in the picture below.
I finally solved my Problem.. It seems to be the
URLEncoder.encode(json.toString(),"UTF-8");
In fact removing it and sending just output.writeBytes(json.toString());
Everything works perfectly
Hi I am new to android and I am trying to connect android to MySQL with php. I want to create a login system where only admin can login.
Below is my code
#Override
protected Boolean doInBackground(Void... params) {
// TODO: attempt authentication against a network service.
Boolean s = true;
String link = "http://localhost/eKos/login.php";
try{
URL url = new URL(link);
String data = URLEncoder.encode("username", "UTF-8") + "=" +
URLEncoder.encode(mUsername, "UTF-8");
data += "&" + URLEncoder.encode("password", "UTF-8") + "=" +
URLEncoder.encode(mPassword, "UTF-8");
URLConnection conn = url.openConnection();
conn.setDoOutput(true);
OutputStreamWriter wr = new OutputStreamWriter(conn.getOutputStream());
wr.write(data);
wr.flush();
BufferedReader reader = new BufferedReader(new
InputStreamReader(conn.getInputStream()));
StringBuilder sb = new StringBuilder();
String line = null;
// Read Server Response
while((line = reader.readLine()) != null) {
sb.append(line);
break;
}
if (sb.toString() != "Login Successful"){
s = false;
}
} catch (Exception e){
System.out.print("Exception: " + e.getMessage());
}
return s;
}
However, it seems like variable s is not modified at all inside the try block since this function always returns true.
Does anyone know how to fix this?
Thank you
try this:
if (!(sb.toString()).equals("Login Successful")){
s = false;
}
} catch (Exception e){
System.out.print("Exception: " + e.getMessage());
s = false;
}
return s;
Also print your server response whether it has Login Successful string in it..
and check if any exception is thrown
Are you using volley?
There is a great tutorial for this : https://www.youtube.com/watch?v=QxffHgiJ64M&list=PLe60o7ed8E-TztoF2K3y4VdDgT6APZ0ka
Why don't you Use "retrofit2" library?! it's far better, faster and easier than AsyncTask or Volly and it doesn't have the complexity of two mentioned libraries. You can use the links blow for more informarion:
https://square.github.io/retrofit/
And
http://www.androidhive.info/2016/05/android-working-with-retrofit-http-library/
In my android app i want to send compressed data to php server using gzip compression and receive response from the server and decompress the response if it is compressed. But when i am sending compressed data,server is getting null and not the data which i am sending and it is returning error message.
This is code i am using for compression--
public static String compress(String strData) throws Exception
{
ByteArrayOutputStream obj = new ByteArrayOutputStream();
GZIPOutputStream gzip = new GZIPOutputStream(obj);
gzip.write(strData.getBytes("UTF-8"));
gzip.close();
String outStr = obj.toString("UTF-8");
return outStr;
}
This is the code used for decomprssion---
public static String decompress(String str) throws Exception
{
byte[] bytes1 = str.getBytes("UTF-8");
GZIPInputStream gis = new GZIPInputStream(new ByteArrayInputStream(bytes1));
BufferedReader bf = new BufferedReader(new InputStreamReader(gis, "UTF-8"));
String outStr = "";
String line;
while ((line=bf.readLine())!=null) {
outStr += line;
}
return outStr;
}
And I also add a header to httppost request
httpPost.addHeader("Accept-Encoding", "gzip, deflate");
can anyone please tell me what to do if I want to compress data before sending to server and also receive response and decompress it, if it is compressed.
public static void main() {
String myString = "H4sIAAAAAAAAA5WMuwrCMBSGX0XOnCFpLoZ0ExH0FaTDyU0DTVsSB6H03Y3dHN3+67fCgm8wjAA6dz2DASmjUsjRCs8tahu5FCw6DQQmzKEt";
byte[] decode = Base64.decode(myString, Base64.NO_WRAP);
ByteArrayInputStream byteArrayInputStream = new ByteArrayInputStream(decode);
int read;
try {
GZIPInputStream gzipInputStream = new GZIPInputStream(byteArrayInputStream);
BufferedReader br = new BufferedReader(new InputStreamReader(gzipInputStream));
System.out.println("read222 :" + br.readLine());
DataInputStream dataInputStream = new DataInputStream(gzipInputStream);
//System.out.println("read222 :" + dataInputStream.retoString());
for (int i = 0; i < decode.length; i++) {
read = dataInputStream.readInt();
int rRead = Integer.reverseBytes(read);
System.out.println("read :" + dataInputStream.read());
}
} catch (IOException e) {
e.printStackTrace();
}
}
run your code in a thread or asynctask or service whereever you want
Thread thread=new Thread(new Runnable()
{
#Override
public void run()
{
try
{
String body = "Naval is working on zip and unzip processed return json";
URL url = new URL("http://yourServerUrl/yourgzip.php");
URLConnection conn = url.openConnection();
conn.setDoOutput(true);
conn.setRequestProperty("Content-encoding", "gzip");
conn.setRequestProperty("Content-type", "application/octet-stream");
GZIPOutputStream dos = new GZIPOutputStream(conn.getOutputStream());
dos.write(body.getBytes());
dos.flush();
dos.close();
BufferedReader in = new BufferedReader(new InputStreamReader(conn.getInputStream()));
StringBuilder builder=new StringBuilder();
String decodedString = "";
while ((decodedString = in.readLine()) != null)
{
builder.append(decodedString);
}
in.close();
Log.e("Data", builder.toString());
}
catch (Exception e)
{
Log.e("Datae", builder.toString());
}
}
});
thread.start();
on server side ask them to use this code
$postdata=gzinflate( substr($HTTP_RAW_POST_DATA,10,-8) );
as $HTTP_RAW_POST_DATA deprecated so use file_get_contents() like to return array
$post = array_map('urldecode',explode('&',file_get_contents("php://input")));
or like this method to decompress a gzip stream that was pushed to my webserver
$x = file_get_contents("compress.zlib://php://input");
and using
$data_as_associate_Array=json_decode($x,true);
How can I get the data this method is forwarding to a PHP webpage ?
URL url;
HttpURLConnection connect = null;
BufferedReader rd;
StringBuilder sb;
OutputStreamWriter wr;
// Change this url to the url of your receiveJsonSms.php.
String urlString = "http://www.paintedostrich.com/receiveJsonSms.php";
try {
System.setProperty("http.keepAlive", "false");
url = new URL(urlString);
connect = (HttpURLConnection) url.openConnection();
connect.setRequestMethod("POST");
connect.setDoOutput(true);
connect.setDoInput(true);
connect.setReadTimeout(10000);
connect.connect();
// write to the stream
String data = URLEncoder.encode("texts", "UTF-8") + "="
+ URLEncoder.encode(jsonTexts.toString(), "UTF-8");
wr = new OutputStreamWriter(connect.getOutputStream());
wr.write(data);
wr.flush();
// read the result from the server
rd = new BufferedReader(new InputStreamReader(connect.getInputStream()));
sb = new StringBuilder();
String line = null;
while ((line = rd.readLine()) != null) {
sb.append(line);
}`
To decode json in PHP use json_decode().
<?php
$json = '{"a":1,"b":2,"c":3,"d":4,"e":5}';
var_dump(json_decode($json));
var_dump(json_decode($json, true));
?>
I think the answer is
sb.ToString();
thats the data you get from the server if you want to read the JSON use this
http://www.codeproject.com/Tips/397574/Use-Csharp-to-get-JSON-data-from-the-web-and-map-i