I'm wondering what the format of a json is suppose to be since it seems php and android has two different types.
When encode the php, it looks like this:
{"id":8435,"name":"Sears"}
{"id":8436,"name":"Sears Appliance Services"}
But when I try to decode in android. It comes out as one big string in android (because it's just viewing the source code of the php page).
This is the code:
Php:
echo json_encode($results[$i]);
Android:
url = new URL("site");
String param = "arg1=" + URLEncoder.encode("value1", "UTF-8");
conn = (HttpURLConnection) url.openConnection();
conn.setDoOutput(true);
conn.setRequestMethod("POST");
conn.setFixedLengthStreamingMode(param.getBytes().length);
conn.setRequestProperty("Content-Type","application/x-www-form- urlencoded");
PrintWriter out = new PrintWriter(conn.getOutputStream());
out.print(param);
out.close();
InputStream is = conn.getInputStream();
BufferedReader reader = new BufferedReader(new InputStreamReader(is));
String s;
while ((s = reader.readLine()) != null) {
result += s;
}
JSONObject jObject = new JSONObject(result);
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!
ByteArrayOutputStream bytearray = new ByteArrayOutputStream();
mBitmapProfile.compress(Bitmap.CompressFormat.JPEG, 100, bytearray);
String base64 = Base64.encodeToString(bytearray.toByteArray(), Base64.DEFAULT);
String data = URLEncoder.encode("SOURCE", "UTF-8") + "=" base64;
String result = getHttpData("http://example/p.php", data);
private String getHttpData(String httpUrl, String param) {
String urlString = httpUrl;
String data = param;
try {
URL url = new URL(urlString);
HttpURLConnection urlConnection = (HttpURLConnection) url.openConnection();
// urlConnection.setConnectTimeout(CONNECTION_TIMEOUT);
// urlConnection.setReadTimeout(DATARETRIEVAL_TIMEOUT);
urlConnection.setRequestMethod("POST");
urlConnection.setDoOutput(true);
OutputStreamWriter wr = new OutputStreamWriter(urlConnection.getOutputStream());
wr.write(data);
wr.flush();
int responseCode = urlConnection.getResponseCode();
if (responseCode == HttpsURLConnection.HTTP_OK) {
BufferedReader br=new BufferedReader(new InputStreamReader(urlConnection.getInputStream()));
String response = "";
String line = "";
while ((line = br.readLine()) != null) {
response+=line;
}
return response;
}
} catch(MalformedURLException e){
e.printStackTrace();
return null;
} catch(IOException e) {
e.printStackTrace();
return null;
}
return "";
}
After base64 encoding the image
Using POST, making requests from Android to PHP will cause problems.
ex)
android send data : /9j/4AAQSkZJRgABAQAAAQABAAD/2wBDAAEBA+BAQEBAQE==
php receive data : /9j/4AAQSkZJRgABAQAAAQABAAD/2wBDAAEBABAQEBAQE
Some special characters are lost.
Why is that so?
The problem is that base64 encoded data can contain '+' characters. In x-www-form-urlencoded data the receiver knows that '+' is an encoding of a space character. Thus since you aren't URL encoding your base64 value, any instances of '+' will cause the data to be corrupted when received.
I am sending user email from Android app to PHP using HttpUrlConnection but PHP is not receiving Any data from App. This type of questions have already been asked but their solution do not worked for me. My Android Coding is
URL server_url = new URL("http://www.myURL.com/Jobs/login.php");
HttpURLConnection urlc = (HttpURLConnection) server_url.openConnection();
urlc.setDoOutput(true);
urlc.setDoInput(true);
urlc.setRequestMethod("POST");
urlc.setRequestProperty("Content-Language", "en-US");
urlc.setRequestProperty("Accept-Encoding", "identity");
urlc.connect();
HashMap<String, String> param = new HashMap<>();
param.put("email", mEmail);
DataOutputStream os = new DataOutputStream(urlc.getOutputStream());
os.writeBytes(URLEncoder.encode(mEmail, "UTF-8"));
os.flush();
os.close();
and My php code is:
<?php
$user_email=$_POST['email'];
echo "Email is $user_email";
?>
but when running this php on browser, it is echoing "Email is" as it is not receiving any data from android. Please Help
My php code contains only these two lines. Am I missing something in php coding?
You're not sending the paramater at all. You need to structure the request much better aswell since it's clear you're getting confused.
URL server_url = new URL("http://www.myURL.com/Jobs/login.php");
HttpURLConnection urlc = (HttpURLConnection) server_url.openConnection();
//header stuff
urlc.setRequestMethod("POST");
urlc.setRequestProperty("Content-Language", "en-US");
urlc.setRequestProperty("Accept-Encoding", "identity");
//params
String urlParameters = "email="+mEmail;
//send post
urlc.setDoOutput(true);
DataOutputStream wr = new DataOutputStream(urlc.getOutputStream());
wr.writeBytes(urlParameters);
wr.flush();
wr.close();
//read result
BufferedReader in = new BufferedReader(
new InputStreamReader(urlc.getInputStream()));
String inputLine;
StringBuffer response = new StringBuffer();
while ((inputLine = in.readLine()) != null) {
response.append(inputLine);
}
in.close();
//print result
System.out.println(response.toString()
);
After so many solutions and discussion finally i got the solution..can not say solution but an alternative approach and it is " volley" library...i used it..and finally php receives the data....
In my project, I'm sending data from an android device and it is inserted into a database using a php script. But the same data is inserted twice. (please see here)
What is wrong with my code?
Android:
try {
String data=URLEncoder.encode("name", "UTF-8")+"="+URLEncoder.encode(Name, "UTF-8");
data+="&"+URLEncoder.encode("family", "UTF-8")+"="+URLEncoder.encode(Family, "UTF-8");
data+="&"+URLEncoder.encode("city", "UTF-8")+"="+URLEncoder.encode(City, "UTF-8");
data+="&"+URLEncoder.encode("ostan", "UTF-8")+"="+URLEncoder.encode(Ostan, "UTF-8");
data+="&"+URLEncoder.encode("tel", "UTF-8")+"="+URLEncoder.encode(Tel, "UTF-8");
data+="&"+URLEncoder.encode("sef", "UTF-8")+"="+URLEncoder.encode(sef1, "UTF-8");
data+="&"+URLEncoder.encode("bod", "UTF-8")+"="+URLEncoder.encode(bodjeh1, "UTF-8");
data+="&"+URLEncoder.encode("tab", "UTF-8")+"="+URLEncoder.encode(tabgh, "UTF-8");
data+="&"+URLEncoder.encode("img", "UTF-8")+"="+URLEncoder.encode(imgs, "UTF-8");
data+="&"+URLEncoder.encode("imgf", "UTF-8")+"="+URLEncoder.encode(fimage, "UTF-8");
URL link=new URL(MainActivity.url+"/app/order.php");
URLConnection con=link.openConnection();
con.setDoOutput(true);
OutputStreamWriter wrw=new OutputStreamWriter(con.getOutputStream());
wrw.write(data);
wrw.flush();
BufferedReader br=new BufferedReader(new InputStreamReader(con.getInputStream()));
StringBuilder sb=new StringBuilder();
String l="";
while((l=br.readLine())!=null){
sb.append(l);
}
r=sb.toString();
br.close();
Code for insertion - php
$name=$_POST['name'];
$family_name=$_POST['family'];
$city=$_POST['city'];
$ostan=$_POST['ostan'];
$tel=$_POST['tel'];
$comment=$_POST['sef'];
$bod=$_POST['bod'];
$tab=$_POST['tab'];
$img=$_POST['img'];
$imgf=$_POST['imgf'];
$sql="INSERT INTO `customer_table`(`id`, `name`, `family_name`, `city`, `ostan`, `tel`, `comment`,`bodjeh`,`tabagheh`,`imag_f`,`image`)
VALUES ('','$name','$family_name','$city','$ostan','$tel','$comment','$bod','$tab','$imgf','$img')";
Please use below method to send data to server
First convert your request json into simple map like
Map<String, String> map = new HashMap<>();
map.put("name", Name);.....so on
Then use below method to call the Webservice.
private JSONObject sendRequest(String urlString, Map<String, String> map, String fileKey, File file) {
StringBuilder strData= null;
JSONObject resObj = null;
try {
Log.i("Send request", urlString+"="+map);
URL url = new URL(urlString);
HttpURLConnection conn = (HttpURLConnection) url.openConnection();
conn.setReadTimeout(50000);
conn.setConnectTimeout(50000);
conn.setRequestMethod("POST");
conn.setUseCaches(false);
conn.setDoInput(true);
conn.setDoOutput(true);
if(map == null)
{
map = new HashMap<>();
}
MultipartEntity reqEntity = new MultipartEntity(HttpMultipartMode.BROWSER_COMPATIBLE);
for (HashMap.Entry<String, String> entry : map.entrySet()) {
String k = entry.getKey();
String v = entry.getValue();
reqEntity.addPart(k, new StringBody(v));
}
if(file != null && !TextUtils.isEmpty(fileKey))
{
FileBody filebody = new FileBody(file, "image/*");
reqEntity.addPart(fileKey, filebody);
}
conn.setRequestProperty("Connection", "Keep-Alive");
conn.addRequestProperty("Content-length", reqEntity.getContentLength() + "");
conn.addRequestProperty(reqEntity.getContentType().getName(), reqEntity.getContentType().getValue());
OutputStream os = conn.getOutputStream();
reqEntity.writeTo(os);
os.close();
conn.connect();
if (conn.getResponseCode() == HttpURLConnection.HTTP_OK) {
BufferedReader reader = new BufferedReader(new InputStreamReader(conn.getInputStream()));
String sResponse;
strData = new StringBuilder();
while ((sResponse = reader.readLine()) != null) {
strData = strData.append(sResponse);
}
}
if(strData != null)
resObj = new JSONObject(strData.toString());
} catch (Exception e) {
e.printStackTrace();
}
return resObj;
}
As your php code you need to do :
$result = mysql_query($sql);
if(count($result) > 0)
{
echo "1";
}else
{
echo "0";
}
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