Send a lot of data from Android device to a server - php

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());

Related

php is not receiving data from android through httpUrlConnection

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....

My android decode doesn't work with php encode

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);

Connect to php page using .htaccess with android application

i've a locked php page (username and password) by .htaccess file, how can i do to connect to this php with my android application? My function to connect is :
String conn(JSONObject json,String page){
String result = "";
String stringaFinale = "";
InputStream is = null;
final int TIMEOUT_MILLISEC = 5000; // = 10 seconds
HttpParams httpParams = new BasicHttpParams();
HttpConnectionParams.setConnectionTimeout(httpParams, TIMEOUT_MILLISEC);
HttpConnectionParams.setSoTimeout(httpParams, TIMEOUT_MILLISEC);
HttpClient client = new DefaultHttpClient(httpParams);
HttpPost request = new HttpPost("http://olbolb.org/Hihi/"+page);
//request result type
request.setHeader("Accept", "application/json; charset=utf-8");
try{ StringEntity se = new StringEntity(json.toString());
se.setContentEncoding(new BasicHeader(HTTP.CONTENT_TYPE,"application/json"));
request.setEntity(se);
HttpResponse response = client.execute(request);
temp= EntityUtils.toString(response.getEntity());
return temp;
}
catch(Exception e){
return null;
}
}
You can add this code for BASIC authentication in HttpPost object:
HttpPost request = new HttpPost("http://olbolb.org/Hihi/"+page);
request.setHeader("Authorization", "Basic " +
new Base64().encodeToString("username:password".getBytes("UTF-8"), Base64.DEFAULT) );

Android: Uploading a file to a page along with other POST strings

I am trying to upload an image to a PHP page along with some other info about the image so the PHP page knows what to do with it. Currently, I am getting away with it using this:
URL url = new URL("http://www.tagverse.us/upload.php?authcode="+WEB_ACCESS_CODE+"&description="+description+"&userid="+userId);
HttpURLConnection connection = (HttpURLConnection)url.openConnection();
connection.setDoOutput(true);
connection.setRequestMethod("POST");
OutputStream os = connection.getOutputStream();
InputStream is = mContext.getContentResolver().openInputStream(uri);
BufferedInputStream bis = new BufferedInputStream(is);
int totalBytes = bis.available();
for(int i = 0; i < totalBytes; i++) {
os.write(bis.read());
}
os.close();
BufferedReader reader = new BufferedReader(new InputStreamReader(connection.getInputStream()));
String serverResponse = "";
String response = "";
while((response = reader.readLine()) != null) {
serverResponse = serverResponse + response;
}
reader.close();
bis.close();
Is there a more elegant solution to this besides having a GET/POST hybrid? I feel as if this is sloppy, but for all I know it is a perfectly acceptable solution. If there is a better way of doing this, I'd appreciate being pointed in the right direction. Thanks!
PS: I am familiar with how you would, under normal conditions, interact with a PHP page via POST:
HttpClient client = new DefaultHttpClient();
HttpPost post = new HttpPost("http://www.tagverse.us/login.php");
try {
List<NameValuePair> pairs = new ArrayList<NameValuePair>();
pairs.add(new BasicNameValuePair("authcode", WEB_ACCESS_CODE));
pairs.add(new BasicNameValuePair("username", username));
pairs.add(new BasicNameValuePair("password", password));
post.setEntity(new UrlEncodedFormEntity(pairs));
client.execute(post);
}
Essentially what I'd like to do is combine these two methods, but because I work with an HttpURLConnection object rather than a HttpPost object, it isn't as simple as just merging the two.
Thank you!
You can try an take a look at the answer I added for this similar question:
https://stackoverflow.com/a/9003674/472747
Here is the code:
byte[] data = {10,10,10,10,10}; // better get this from a file or memory
HttpClient httpClient = new DefaultHttpClient();
HttpPost postRequest = new HttpPost("server url");
ByteArrayBody bab = new ByteArrayBody(data, "image.jpg");
MultipartEntity reqEntity = new MultipartEntity(HttpMultipartMode.BROWSER_COMPATIBLE);
reqEntity.addPart("image", bab);
FormBodyPart bodyPart=new FormBodyPart("formVariableName", new StringBody("formValiableValue"));
reqEntity.addPart(bodyPart);
bodyPart=new FormBodyPart("formVariableName2", new StringBody("formValiableValue2"));
reqEntity.addPart(bodyPart);
bodyPart=new FormBodyPart("formVariableName3", new StringBody("formValiableValue3"));
reqEntity.addPart(bodyPart);
postRequest.setEntity(reqEntity);
HttpResponse response = httpClient.execute(postRequest);
BufferedReader in = new BufferedReader(new InputStreamReader(response.getEntity().getContent()));
String line = null;
while((line = in.readLine()) != null) {
System.out.println(line);
}

HTTP post from android to PHP not working

I am trying to get a Android device to send some information to a local host. I believe I have the Android sending the information, but my PHP code is not accepting or not displaying the code. I have attached my code, is there something I have missed? I am running wamp server also, and have put the permissions into the manifest.
Java Code: #
HttpPost httppost;
HttpClient httpclient;
// List with arameters and their values
List<NameValuePair> nameValuePairs;
String serverResponsePhrase;
int serverStatusCode;
String bytesSent;
String serverURL = "http://10.0.2.2/test/index.php";
httppost = new HttpPost(serverURL);
httpclient = new DefaultHttpClient();
nameValuePairs = new ArrayList<NameValuePair>(2);
// Adding parameters to send to the HTTP server.
nameValuePairs.add(new BasicNameValuePair("parameterName1", "git"));
nameValuePairs.add(new BasicNameValuePair("parameterName2", "git"));
// Send POST message with given parameters to the HTTP server.
try {
httppost.setEntity(new UrlEncodedFormEntity(nameValuePairs));
HttpResponse response = httpclient.execute(httppost);
InputStream is = response.getEntity().getContent();
BufferedInputStream bis = new BufferedInputStream(is);
ByteArrayBuffer baf = new ByteArrayBuffer(20);
int current = 0;
while ((current = bis.read()) != -1) {
baf.append((byte) current);
}
bytesSent = new String(baf.toByteArray());
// Response from the server
serverResponsePhrase = response.getStatusLine().getReasonPhrase();
serverStatusCode = response.getStatusLine().getStatusCode();
System.out.println("COMPLETE");
} catch (Exception e) {
// Exception handling
System.out.println("Problem is " + e.toString());
}
PHP Code:
<?php
echo "param1 value: ".$_POST['parameterName1']."\n";
echo "param2 value: ".$_POST['parameterName2']."\n";
?>
I also tried this code, but it did not work with my PHP
HttpPost httppost;
HttpClient httpclient;
// List with arameters and their values
List<NameValuePair> nameValuePairs;
String serverResponsePhrase;
int serverStatusCode;
String bytesSent;
String serverURL = "http://10.0.2.2/test/index.php";
httppost = new HttpPost(serverURL);
httpclient = new DefaultHttpClient();
nameValuePairs = new ArrayList<NameValuePair>(2);
// Adding parameters to send to the HTTP server.
nameValuePairs.add(new BasicNameValuePair("'parameterName1'", "git"));
nameValuePairs.add(new BasicNameValuePair("'parameterName2'", "git"));
// Send POST message with given parameters to the HTTP server.
try {
HttpEntity entity = new UrlEncodedFormEntity(nameValuePairs);
httppost.addHeader(entity.getContentType());
httppost.setEntity(entity);
HttpResponse response = httpclient.execute(httppost);
InputStream is = response.getEntity().getContent();
BufferedInputStream bis = new BufferedInputStream(is);
ByteArrayBuffer baf = new ByteArrayBuffer(20);
int current = 0;
while ((current = bis.read()) != -1) {
baf.append((byte) current);
}
bytesSent = new String(baf.toByteArray());
// Response from the server
serverResponsePhrase = response.getStatusLine().getReasonPhrase();
serverStatusCode = response.getStatusLine().getStatusCode();
System.out.println("response" + response.toString());
System.out.println("COMPLETE");
} catch (Exception e) {
// Exception handling
System.out.println("Problem is " + e.toString());
}
Make sure the Content-Type HTTP header is getting set. Try replacing
httppost.setEntity(new UrlEncodedFormEntity(nameValuePairs));
with this
HttpEntity entity = new UrlEncodedFormEntity(nameValuePairs);
httppost.addHeader(entity.getContentType());
httppost.setEntity(entity);
Also, instead of response.toString(), try EntityUtils.toString(response.getEntity()) if you want to see the body of the response

Categories