I made a php application at the following url: http://localhost/index.php/registration/returnItemJson to return this valid json:
{"name":"test","price":30,"description":"is this working"}
In my android studio app, I am trying to read it with this:
URL url = new URL(strings[0]);
connection = (HttpURLConnection) url.openConnection();
connection.setRequestMethod("GET");
connection.setDoInput(true);
connection.setDoOutput(true);
connection.connect();
int response = connection.getResponseCode();
Log.d("TAG", "Response code "+response);
StringBuilder result = new StringBuilder();
reader = new BufferedReader(new InputStreamReader(connection.getInputStream()));
String line;
while(null != (line = reader.readLine())){
result.append(line).append("\n");
}
But I am getting an IO exception by connection.GetInputStream().
It works ok when I do this with some other url that returns json, but not with localhost.
Use 10.0.2.2 instead to access your local host. Read more here
Related
I'm having troubles with encoding text from Android EditText when sending it with JSON to PHP script.
First in Android I get the text from EditText element.
String s = editText.getText().toString();
then I post it throught HttpURLConnection to PHP script
HttpURLConnection conn = (HttpURLConnection) url.openConnection();
conn.setRequestMethod("POST");
conn.setRequestProperty("Content-Type", "application/json;charset=UTF-8");
conn.setRequestProperty("Accept", "application/json");
conn.setDoOutput(true);
conn.setDoInput(true);
JSONObject jsonParam = new JSONObject().put("mystring", s);
DataOutputStream os = new DataOutputStream(conn.getOutputStream());
os.writeBytes(jsonParam.toString());
os.flush();
os.close();
then I parse the JSON in PHP script:
$data = json_decode(utf8_decode(file_get_contents('php://input')), true);
Everything works fine, but when I try to send some text with diacritics it seems that nothing is send and var_dump($data) is null. Is there something wrong with the formating or what could be the problem?
Thanks for help.
EDIT
Elsunhoty answer works but I have to use urldecode() in PHP
you can try to trim Your Text First
String s = editText.getText().toString();
s = s.trim();
and then Encode the Text
String encodeText= "";
try {
encodeText= URLEncoder.encode(s,"utf-8");
} catch (UnsupportedEncodingException e) {
e.printStackTrace();
}
I try post json from Android client to PHP server but failed, server cannot receive any data, I don't see what's wrong with it, so I need help, thanks a lot.
this is Android client kernel code:
String result;
String encoding="UTF-8";
String params="{\"name\":\"123\",\"pass\":\"456\"}";
try {
byte[] data=params.getBytes(encoding);
URL urls=new URL(url);
HttpURLConnection conn=(HttpURLConnection) urls.openConnection();
conn.setRequestMethod("POST");
conn.setDoOutput(true);
conn.setRequestProperty("Content-Type", "application/x-javascript; charset="+ encoding);
conn.setRequestProperty("Content-Length", String.valueOf(data.length));
conn.setReadTimeout(4000);
OutputStream outStream = conn.getOutputStream();
outStream.write(data);
outStream.flush();
outStream.close();
BufferedReader bfread=new BufferedReader(new InputStreamReader(conn.getInputStream()));
String str;
StringBuffer resb=new StringBuffer();
while ((str=bfread.readLine())!=null)
{
resb.append(str);
}
result=resb.toString();
and this is server code:
<?php
$data = file_get_contents('php://input');
if(empty($data))
{
echo "no post data";
}
else
{
print_r($data);
}
?>
android client get the message from server and print on screen, they always show "no post data", obviously client visit server successful, but server not received any data. Then I write a test HTML page to post the data with form, it works. I don't know why.
We are trying to send a large JSON object (with 100+ key value pairs) from an android app to server using following code.
URL url = new URL(urlString);
HttpURLConnection urlConnection = (HttpURLConnection) url.openConnection();
JSONObject dt = new JSONObject();
try {
dt.put("test", "test");
} catch (JSONException e) {
e.printStackTrace();
}
urlConnection.setDoOutput(true);
// is output buffer writter
urlConnection.setRequestMethod("POST");
urlConnection.setRequestProperty("Content-Type", "application/json");
urlConnection.setRequestProperty("Accept", "application/json");
//set headers and method
Writer writer = new BufferedWriter(new OutputStreamWriter(urlConnection.getOutputStream(), "UTF-8"));
writer.write(String.valueOf(dt));
// json data
writer.close();
and in server side PHP,
$data = json_decode(file_get_contents('php://input'));
echo (string) $data;
But it returns blank value, how can we pass the JSON object from android app to server?
EDIT: We able to get the raw data without decoding by file_get_contents('php://input') as {"test1":1234567890,"test2":"test"} but when using json_decode it returns blank value. We also tried with returning data withUTF-8 encoded format which sends data as %7B%22test1%22%3A1234567890%2C%22test2%22%3A%22test%22%7D in raw format but it also unable to decode. BTW, json_last_error() returns 4.
I'm new to Android and after a long time I finally manage to create a database using PHP scripts and MySQL.
While I'm using the Android Studio emulator I do succeed sending data to the database but when I run the application on my device I failed to do so.
I don't get any error and the app keeps running (not crushing) but the database doesn't get the data.
This is the doInbackground method in my BackgroundTask class:
#Override
// send info to MySQL DB
// it gets 4 parameters - the first if the opertaion should be "register" and the others are
// user info (name,pass,gender)
protected String doInBackground(String... params) {
// the ip is default for localhost
String reg_url = "http://**MyIP**/webapp/register.php";
String login_url = "http://**MyIP**/webapp/login.php";
String method = params[0];
if (Objects.equals(method, "register")){
String userName = params[1];
String userPass = params[2];
String gender = params[3];
try {
URL url = new URL(reg_url);
// run the register php script.
HttpURLConnection httpURLConnection = (HttpURLConnection) url.openConnection();
httpURLConnection.setRequestMethod("POST");
httpURLConnection.setDoOutput(true);
OutputStream OS = httpURLConnection.getOutputStream();
BufferedWriter bufferedWriter = new BufferedWriter(new OutputStreamWriter(OS, "UTF-8"));
// applied the "userName,"userPass" and "gender" that I define in the POST (at the register.php)
// the info the user typed.
String data = URLEncoder.encode("userName", "UTF-8") + "=" + URLEncoder.encode(userName,"UTF-8") + "&" +
URLEncoder.encode("userPass", "UTF-8") + "=" +URLEncoder.encode(userPass,"UTF-8") + "&" +
URLEncoder.encode("gender", "UTF-8") + "=" +URLEncoder.encode(gender,"UTF-8");
// write the data to server
bufferedWriter.write(data);
bufferedWriter.flush();
bufferedWriter.close();
OS.close();
InputStream IS = httpURLConnection.getInputStream();
IS.close();
return "Registration Successs";
} catch (MalformedURLException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
}
return null;
}
you want to do setting of the wampp server in your pc. i will give a URL for doing your work. please any query ask for it.
http://androidcss.com/android/test-android-app-php-localhost-wamp/
Connect your PC and android device to same wifi network.
If your running on windows enter ipconfig on cmd and if it is ubuntu run ifconfig on terminal to get ip address
it'll be like 192.168.0.*. If **MyIP** and IP Address which you've got are same then ignore it.
Be Sure that you've given permissions to access internet in manifest file.
Android cannot get data when I include function.php file.But Android get data when I remove file include code in current php file.How to solve this error.I wanna use some function in function.php file.So I must use include code to call function.php.
I've no idea.is it android or php fault?
My PHP version : 5.3.10
apache version : 2.2.21
My android code:
HttpClient client = new DefaultHttpClient();
HttpConnectionParams.setConnectionTimeout(client.getParams(), 500000);
HttpConnectionParams.setSoTimeout(client.getParams(), 500000);
HttpUriRequest request = new HttpGet(CategoryAPI);
HttpResponse response = client.execute(request);
InputStream atomInputStream = response.getEntity().getContent();
BufferedReader in = new BufferedReader(new InputStreamReader(atomInputStream));
String line;
String str = "";
while ((line = in.readLine()) != null){
str += line;
}
// parse json data and store into arraylist variables
JSONObject json = new JSONObject(str);
JSONArray data = json.getJSONArray("data");
for (int i = 0; i < data.length(); i++) {
JSONObject object = data.getJSONObject(i);
JSONObject feed = object.getJSONObject("Feeds");
FeedItem.allFeedItemsList.add(new FeedItem(Integer.parseInt(feed.getString("id")), feed.getString("name"), feed.getString("post_img"), feed.getString("post_description"), feed.getString("userimage"), feed.getString("post_date"), feed.getString("post_title")));
}
Anyone can help??????????
Now i can solve my error by Encoding in ANSI. Since I Encode in UTF-8, android can't load. Now, It is fine and ok. Thanks.......
Try using this library:-https://github.com/Abhishekpalodath/FetchServerUtil-Android.git.
You can also load real-time data using this.