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....
Related
The code requests HTTP connection to server that runs with php (phpMyAdmin).
It gives response with JSONObject.
It worked when I was testing in Asia, however it gives different response in the United States.
With given url:
target = "http://example.com/request.php?value=DDPS"
This works on web browser but in Android device it gives:
<html><body><script type="text/javascript" src="/cupid.js"></script><script>
.....path=/";location.href="http://example.com/request.php?value=DDPS
&ckattempt=1";</script></body></html>
This fails to create JSONObject which is obvious.
What would be possible problem on this behavior?
I have set permission to server that allows access from all continents.
Here is my httpURLconnection code:
try{
URL url = new URL(target);
HttpURLConnection httpURLConnection = (HttpURLConnection)url.openConnection();
httpURLConnection.setInstanceFollowRedirects(true);
InputStream inputstream = httpURLConnection.getInputStream();
BufferedReader bufferedReader = new BufferedReader(new InputStreamReader(inputstream));
String temp;
StringBuilder stringBuilder = new StringBuilder();
while((temp = bufferedReader.readLine()) != null)
{
stringBuilder.append(temp).append("\n");
}
bufferedReader.close();
inputstream.close();
httpURLConnection.disconnect();
return stringBuilder.toString().trim();
}catch (Exception e) {
e.printStackTrace();
}
EDIT:
HttpURLConnection.setFollowRedirects(true);
gives same behavior.
Here is my php code for getting data from database and send response in JSON format.
On which point should I implement file_get_contents?
<?php
header("Content-Type: text/html; charset=UTF-8");
$con = mysqli_connect("localhost", "exampleID", "examplePW", "exampleID");
$value = $_GET["title"];
$result = mysqli_query($con, "SELECT * FROM DB WHERE title = '$value'");
$response = array();
while($row = mysqli_fetch_array($result)){
array_push($response, array("item1"=>$row[1], "item2"=>$row[2], "item3"=>$row[3], "item4"=>$row[4]));
}
echo json_encode(array("response"=>$response), JSON_UNESCAPED_UNICODE);
mysqli_close($con);
?>
probably issue with server redirects. Android gets the first response. you could verify it with using a php scropt and file_get_contents method
You can also try
HttpURLConnection.setFollowRedirects(true);
Solved.
There was no issue in android codes.
The issue was from the server I was connecting to.
It blocked some unknown IP addresses, so I needed to give permission to server to accept certain IP access.
I want to send data from android to php.Am using android api 23 and from android's developers site a got to know that namepairvalue is deprecated from api 22 and above. I referred to one of the post here in stackoverflow and got the below code. but still it doesn't work.
My problem is that am sending a value(ID) to php code and based on that value fetching the records from database. Now if i fetch data without using this value it works fine, but i am unable to send the id value to php code.
i am unable to find whats wrong in this code or may be my fault is editing the code. It would be great if someone helps me to understand it clearly .
Thank you in advance.
Here is the code snippet that i have tried.
Android Code:
String sid = staffid.toString(); // this sid is passed as intent from another activity and passing it to below link.
Log.d("SID :", "" + sid);
try {
URL url = null;
url = new URL("http://usplhubli.96.lt/hrm/hrm_app/individual_view_staff.php");
Log.d("url to display :", "" + url.toString());
HttpURLConnection conn = null;
conn = (HttpURLConnection) url.openConnection();
conn.setReadTimeout(CONNECTION_TIMEOUT);
conn.setConnectTimeout(CONNECTION_TIMEOUT);
conn.setRequestMethod("POST");
conn.setDoInput(true);
conn.setDoOutput(true);
DataOutputStream os = new DataOutputStream(conn.getOutputStream());
// Log.d("os to display :", "" + os.toString());
Uri.Builder builder = new Uri.Builder().appendQueryParameter("sid", sid);
Log.d("builder to display :", "" + builder.toString());
String query = builder.build().getEncodedQuery();
BufferedWriter writer = new BufferedWriter(new OutputStreamWriter(os, "UTF-8"));
Log.d("writer display :", "" + writer.toString());
writer.write(query);
writer.flush();
writer.close();
os.close();
} catch (MalformedURLException e1) {
e1.printStackTrace();
} catch (ProtocolException e2) {
e2.printStackTrace();
} catch (IOException e3) {
e3.printStackTrace();
}
return null;
}
I have this code in doInBackground(String... params) of AsyncTask
based on this sid value i have to get the data from database and display it in android activity.
Here is the PHP code that i have tried
PHP Code:
$response=array();
$sid=$_POST["sid"]; // this is the POST data that am send from android
//$sid="4"; // this is the static value that i have tried and its working
print_r($sid);
include 'dbconfig.php';
$imagePath='http://www.usplhubli.96.lt/hrm';
$query=mysqli_query($conn,"select * from hrm_staff where sid='$sid'");
if(mysqli_num_rows($query) >0) {
$response["hrm_staff"] = array();
while ($row = mysqli_fetch_array($query)) {
$recp = array();
$recp["sid"]=$row["sid"];
$fullName=$row['fname']."".$row['mname']."".$row['lname'];
$recp["name"]= $fullName;
$recp["address"]=$row['address'];
$recp['city']=$row['city'];
$recp["design"]=$row['did'];
$recp["contact"]=$row['mobile'];
$recp["email"]=$row['email'];
$recp['qualification']=$row['quali'];
$recp["dateofjoining"]=$row['doj'];
$ppic1=$row['ppic'];
$ppic1;
$ppic21=$imagePath."/".trim($ppic1);
$recp["ppic"]= $ppic21;
array_push($response["hrm_staff"], $recp);
}
$response["success"] = 1;
$response["message"]="display records";
echo json_encode($response);
}
else
{
$response["success"] = 0;
$response["message"] = "No products found";
echo json_encode($response);
}
Please suggest. Thank you.
use these lines of code for using HttpURLConnection
For sending the request parameter are as:-
Uri.Builder builder = new Uri.Builder()
.appendQueryParameter("phone", number)
.appendQueryParameter("password", password)
.appendQueryParameter("device_login",value);
And for the getting the request parameter in the post method of connectionUrl are as follow:-
URL url = new URL(myurl);
HttpURLConnection urlConnection = (HttpURLConnection) url.openConnection();
urlConnection.setReadTimeout(30000);
urlConnection.setConnectTimeout(30000); ;
String query = builder.build().getEncodedQuery();
System.out.println("REQUEST PARAMETERS ARE===" + query);
urlConnection.setRequestMethod("POST");
urlConnection.setDoInput(true);
urlConnection.setDoOutput(true);
urlConnection.connect();
//Send request
DataOutputStream wr = new DataOutputStream (
urlConnection.getOutputStream ());
wr.writeBytes (query);
wr.flush ();
wr.close ();
//Get Response
InputStream isNew = urlConnection.getInputStream();
BufferedReader rd = new BufferedReader(new InputStreamReader(isNew));
String line;
response = new StringBuffer();
while((line = rd.readLine()) != null) {
response.append(line);
}
rd.close();
System.out.println("Final response===="+response);
There might be more than one issue but a big one is you never send the request, all you are doing is creating the request and setting up the parameters
you need to do a
conn.connect();
or
conn.getInputStream();
or any number of things you can do to send the request and get the information you require
AFTER you write your params
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);
I need to send a lot of data from my csv in my Android device to a webpage on my server for building a lot of SQL query on my php.
A lot of people speak about using JSON for android, and others people about sending an array of array of array of string by using something like this :
String dataPOST = URLEncoder.encode("table") + "=" + URLEncoder.encode(tableName) + "&" + URLEncoder.encode("data") + "="
+ URLEncoder.encode(sb.toString())+ "&" + URLEncoder.encode("idvente") + "="
+ URLEncoder.encode(idvente);
URL url = new URL(link);
URLConnection conn = url.openConnection();
conn.setDoOutput(true);
OutputStreamWriter wr = new OutputStreamWriter(conn.getOutputStream());
wr.write(dataPOST);
wr.flush();
But I fear for the limitation of php/my server cause it can be a lot data.
What is the best solution for my problem ?
Thank you and sorry for the mistakes in english, I'm not fluent xD !
You can make POST request using MultipartEntity. You can put any string and files to request body:
HttpParams params = new BasicHttpParams();
params.setParameter(CoreProtocolPNames.PROTOCOL_VERSION, HttpVersion.HTTP_1_1);
HttpClient httpClient = new DefaultHttpClient(params);
try {
HttpPost httpPost = new HttpPost(YOUR_URL);
MultipartEntity multipartEntity = new MultipartEntity();
multipartEntity.addPart("param1", new StringBody("param1 value", Charset.forName("UTF-8")));
multipartEntity.addPart("param2", new StringBody("param2 value", Charset.forName("UTF-8")));
if (imagePath.length() > 0) {
multipartEntity.addPart("images", new FileBody(new File(imagePath)));
}
httpPost.setEntity(multipartEntity);
String resp = httpClient.execute(httpPost, new BasicResponseHandler());
} catch (Exception e) {
}
Also You can try UrlEncodedFormEntity. It also has not restrictions of string length.
HttpPost httpPost = new HttpPost(sb.toString());
List<NameValuePair> entityParams = new ArrayList<NameValuePair>();
entityParams.add(new BasicNameValuePair("action", "postcomment"));
entityParams.add(new BasicNameValuePair("app_id", com.appbuilder.sdk.android.Statics.appId));
entityParams.add(new BasicNameValuePair("token", com.appbuilder.sdk.android.Statics.appToken));
entityParams.add(new BasicNameValuePair("module_id", Statics.MODULE_ID));
entityParams.add(new BasicNameValuePair("parent_id", pVideoItem.getId() + ""));
httpPost.setEntity(new UrlEncodedFormEntity(entityParams, "utf-8"));
String resp = httpClient.execute(httpPost, new BasicResponseHandler());
I know this has answers here and there, but I couldn't make any of them work. Does anybody know a good reference, or a tutorial for this, maybe also post here?
What I need to do is :
1) provide a button, that opens the camera application. I have done this by a startResultActivity()
2) user takes the photo, and returns to the application, with the photo saved, preferably with a preview in an ImageView. I tried something, but I cannot test in an emulated device.
3) presses a "send" button, and the application sends the picture to HTTP POST. With "multipart", whatever that is. The php developer does not want me to send the picture as a string converted from a bitmap array.
Any help for this will be appreciated. Thanks !
This link should be more than sufficient for clicking, saving and getting path of an image:
Capture Images
This is the class i wrote for uploading images via HTTP POST:
public class MultipartServer {
private static final String TAG = "MultipartServer";
private static String crlf = "\r\n";
private static String twoHyphens = "--";
private static String boundary = "*****";
private static String avatarPath = null;
public static String postData(URL url, List<NameValuePair> nameValuePairs) throws IOException {
HttpURLConnection connection = (HttpURLConnection) url.openConnection();
connection.setReadTimeout(10000);
connection.setConnectTimeout(15000);
connection.setRequestMethod("POST");
connection.setUseCaches(false);
connection.setDoInput(true);
connection.setDoOutput(true);
connection.setRequestProperty("Connection", "Keep-Alive");
connection.setRequestProperty("Cache-Control", "no-cache");
connection.setRequestProperty("Content-Type", "multipart/form-data;boundary=" + boundary);
String avatarName = null;
StringBuilder query = new StringBuilder();
boolean first = true;
for (NameValuePair pair : nameValuePairs) {
if (first)
first = false;
else
query.append("&");
query.append(URLEncoder.encode(pair.getName(), "UTF-8"));
query.append("=");
query.append(URLEncoder.encode(pair.getValue(), "UTF-8"));
if ((avatarName = pair.getName()).equals("avatar")) {
avatarPath = pair.getValue();
}
}
FileInputStream inputStream;
OutputStream outputStream = connection.getOutputStream();
DataOutputStream dataOutputStream = new DataOutputStream(outputStream);
dataOutputStream.writeBytes(query.toString());
// Write Avatar (if any)
if(avatarName != null && avatarPath != null) {
dataOutputStream.writeBytes(twoHyphens + boundary + crlf);
dataOutputStream.writeBytes("Content-Disposition: form-data; name=\"" + avatarName + "\";filename=\"" + new File(avatarPath).getName() + "\";" + crlf);
dataOutputStream.writeBytes(crlf);
/*Bitmap avatar = BitmapFactory.decodeFile(avatarPath);
avatar.compress(CompressFormat.JPEG, 75, outputStream);
outputStream.flush();*/
inputStream = new FileInputStream(avatarPath);
byte[] data = new byte[1024];
int read;
while((read = inputStream.read(data)) != -1)
dataOutputStream.write(data, 0, read);
inputStream.close();
dataOutputStream.writeBytes(crlf);
dataOutputStream.writeBytes(twoHyphens + boundary + twoHyphens + crlf);
}
dataOutputStream.flush();
dataOutputStream.close();
String responseMessage = connection.getResponseMessage();
Log.d(TAG, responseMessage);
InputStream in = connection.getInputStream();
BufferedReader bufferedReader = new BufferedReader(new InputStreamReader(in, "UTF-8"));
StringBuilder response = new StringBuilder();
char []b = new char[512];
int read;
while((read = bufferedReader.read(b))!=-1) {
response.append(b, 0, read);
}
connection.disconnect();
Log.d(TAG, response.toString());
return response.toString();
}
}
Usage is quite simple: call this static method and pass the path of your image like:
List<NameValuePair> nameValuePairs = new ArrayList<NameValuePair>();
nameValuePairs.add(new BasicNameValuePair("avatar", imagePath));
and finally:
MultipartServer.postData(url, nameValuePairs);
and don't forget to call this function in a separate thread or you'll get NetworkOnMainThreadException.. :)
Update
I'd recommend not to reinvent the wheel & use OkHttp instead. Do checkout the Recipes page. Disclaimer: I'm not a contributor to the project, but I love it. Thanks to Square team.