Uploading Image using Base64 results in error 413 - java

So I'm moving hosting packages from bluehost to namecheap. I'm currently developing an Android application for a university problem. The image upload worked fine on the bluehost webhost. However when I try do the same technique I run into an error.
I've done some debugging and have come to the conclusion that it's server-side related as it's the same code but with parameters changed and nothing on android throws up any errors whatsoever. The entries get added to the database but the image doesn't get uploaded (registration system).
Error:
413 Request Entity Too Large
Request Entity Too Large
The requested resource does not allow request data with GET requests, or the amount of data provided in the request exceeds the capacity limit.
Additionally, a 404 Not Found error was encountered while trying to use an ErrorDocument to handle the request.
PHP Code:
$user = $_POST['userName'];
$base = $_REQUEST['image'];
$binary = base64_decode($base);
header('Content-Type: bitmap; charset=utf-8');
mkdir('../usr/'.$user);
$file = fopen('../usr/'.$user.'/display_picture.png', 'wb');
fwrite($file, $binary);
fclose($file);
Java Code: (Just incase)
public void uploadDisplayPicture(final ProgressDialog uploadingImage) {
final String UPLOAD_DISPLAY_PICTURE = "Upload Display Picture";
new AsyncTask<Void, Void, String>() {
#Override
protected String doInBackground(Void... params) {
Log.d(UPLOAD_DISPLAY_PICTURE,"Do In Background Running");
InputStream is;
try {
ArrayList<NameValuePair> nameValuePairs = new ArrayList<NameValuePair>();
nameValuePairs.add(new BasicNameValuePair("userName", registrationDetails[0]));
nameValuePairs.add(new BasicNameValuePair("image", encodedString));
HttpClient httpclient = new DefaultHttpClient();
HttpPost httppost = new HttpPost(Config.IP + Config.DISPLAY_PHOTO_PATH);
httppost.setEntity(new UrlEncodedFormEntity(nameValuePairs));
HttpResponse response = httpclient.execute(httppost);
HttpEntity entity = response.getEntity();
is = entity.getContent();
BufferedReader reader = new BufferedReader(new InputStreamReader(is, "iso-8859-1"), 8);
StringBuilder sb = new StringBuilder();
String line;
while ((line = reader.readLine()) != null) sb.append(line + "\n");
String resString = sb.toString();
is.close();
Log.d("Http Post Response:", response.toString());
Log.d("Http Response:", resString);
} catch (Exception e) {
System.out.println("Error: " + e);
}
return "";
}
#Override
protected void onPostExecute(String msg) {
Log.d(UPLOAD_DISPLAY_PICTURE, "On Post Execute Running");
super.onPostExecute(msg);
uploadingImage.setMessage("Registering User Details...");
new registerUserDetails().execute(registrationDetails);
}
}.execute(null, null, null);
}

Related

No response from HTTP request

i have written an android app which post data to my database. The app should access an webservice which post the data to the database. the webservice works fine. ive testet it with my browser, he is already on the server. now i want my app to execute the webservice. but that doesnt work. My debugger doesnt work too so im not able to debug. here is my code to for accessing the webservice. any ideas??
public class PostBlog extends AsyncTask<String, Void, String> {
String BlogURL;
public PostBlog(String insertBlogURL) {
BlogURL = insertBlogURL;
}
#Override
protected String doInBackground(String... params) {
postBlogData(BlogURL);
return null;
}
public void postBlogData(String url) {
String result = "";
//the year data to send
ArrayList<NameValuePair> nameValuePairs = new ArrayList<NameValuePair>();
nameValuePairs.add(new BasicNameValuePair("year", "1980"));
//http post
try {
HttpClient httpclient = new DefaultHttpClient();
HttpPost httppost = new HttpPost(url);
httppost.setEntity(new UrlEncodedFormEntity(nameValuePairs));
HttpResponse response = httpclient.execute(httppost);
HttpEntity entity = response.getEntity();
InputStream is = entity.getContent();
BufferedReader reader = new BufferedReader(new InputStreamReader(is, "iso-8859-1"), 8);
StringBuilder sb = new StringBuilder();
String line = null;
while ((line = reader.readLine()) != null) {
sb.append(line + "\n");
}
is.close();
result = sb.toString();
} catch (Exception e) {
//(TextView)rootView.findViewById(R.id.question)
Log.e("log_tag", "Error converting result " + e.toString());
}
}
}
The Class is called from my main Activity by
new PostBlog(insertBlogURL).execute("");
Is there another easier way to execute my ".jsp?asdd=sdsd" file on the server?
Thanks for your ideas.
Instead of doing :
new PostBlog(insertBlogURL).execute("");
Change your constructor and retrieve the url from the doInBackground method, by doing params[0]
Then initiate the download like this
PostBlog blogPoster = new PostBlog();
try {
blogPoster.execute(insertBlogURL);
} catch (InterruptedException e) {} catch (ExecutionException e) {}
I should say this is a modified snippet of code from my own project, so it might not work exactly the way you expect.

Java (Android) HTTP Post to PHP Page

This is for an Android application ,where my mobile developer is trying to post json data to my PHP page .
Below is the function that is being used :
public static String postData(String url, String postData) {
// Create a new HttpClient and Post Header
InputStream is = null;
StringBuilder sb = null;
String result = "";
// StrictMode.ThreadPolicy policy = new StrictMode.ThreadPolicy.Builder().permitAll().build();
// StrictMode.setThreadPolicy(policy);
HttpClient httpclient = new DefaultHttpClient();
HttpPost httppost = new HttpPost(url);
try {
httppost.setEntity(new StringEntity(postData));
httppost.setHeader("Accept", "application/json");
httppost.setHeader("Content-type", "application/json");
// Execute HTTP Post Request
HttpResponse response = httpclient.execute(httppost);
HttpEntity entity = response.getEntity();
is = entity.getContent();
} catch (Exception e) {
Log.e("log_tag", "Error in http connection" + e.toString());
//throw new CustomException("Could not establish network connection");
}
try {
BufferedReader reader = new BufferedReader(new InputStreamReader(
is, "utf-8"), 8);
sb = new StringBuilder();
sb.append(reader.readLine() + "\n");
String line = "0";
while ((line = reader.readLine()) != null) {
sb.append(line + "\n");
}
is.close();
result = sb.toString();
} catch (Exception e) {
Log.e("log_tag", "Error converting result " + e.toString());
//throw new CustomException("Error parsing the response");
}
return result;
}
Where url is the link to my php webpage . On my php page , i am just trying to print out the posted data by doing :
print_r($_POST);
But it shows an empty array . I even tried using the REST addon for firefox and doing the same but it simply shows a blank array .
Would be great if someone could point out if i am missing anything .
Thanks.
you need to get the json content like below :
if(isset($_POST))
{
$json = file_get_contents('php://input');
$jsonObj = json_decode($json);
echo $jsonObj;
}

How to call a php file and store the json output

I am developing an android app, I have run into a situation where the app will use an API to send some data to the php webservice and the webservice will greate some json encoded message which will be echoed back.
My question is
How Do I store this json message that was sent by php echo into a variable in the android app?
How Do I then go about parsing the json and use the data to construct a switch case?
I had raised a similar question sometime back and was told to use AsyncTask but what I don't understand is why would I need to use it.
The sample json response that will be sent by the phpwebservice is
{"error":false,"message":"New user created"}
I want to be able to get the error variable and decide if there is any error and also get the message in a variable and display it to the user in the app.
I currently have the android signup.java code like this
public void post() throws UnsupportedEncodingException
{
// Get user defined values
uname = username.getText().toString();
email = mail.getText().toString();
password = pass.getText().toString();
confirmpass = cpass.getText().toString();
phone = phn.getText().toString();
HttpClient httpclient = new DefaultHttpClient();
HttpResponse httpResponse = null;
HttpPost httppost = new HttpPost("http://www.rgbpallete.in/led/api/signup");
if (password.equals(confirmpass)) {
try {
List<NameValuePair> nameValuePairs = new ArrayList<NameValuePair>(4);
nameValuePairs.add(new BasicNameValuePair("uname", uname));
nameValuePairs.add(new BasicNameValuePair("pass", password));
nameValuePairs.add(new BasicNameValuePair("email", email));
nameValuePairs.add(new BasicNameValuePair("phone", phone));
httppost.setEntity(new UrlEncodedFormEntity(nameValuePairs));
httpResponse = httpclient.execute(httppost);
//Code to check if user was successfully created
final int statusCode = httpResponse.getStatusLine().getStatusCode();
switch (statusCode)
{
case 201:
Toast.makeText(getBaseContext(), "Successfully Registered", Toast.LENGTH_SHORT).show();
break;
case 400:
Toast.makeText(getBaseContext(), "Username already taken", Toast.LENGTH_SHORT).show();
username.setText("");
break;
default:
Toast.makeText(getBaseContext(), "Unknown error occurred", Toast.LENGTH_SHORT).show();
}
} catch (ClientProtocolException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
}
else
{
Toast.makeText(getBaseContext(), "Password mismatch", Toast.LENGTH_SHORT).show();
//Reset password fields
pass.setText("");
cpass.setText("");
}
}
While this checks the http header code and might work( I havent tested it out) I want to use the jsnon response and do the handling using it.
Use java-json:
HttpURLConnection urlConnection = (HttpURLConnection) (uri.toURL().openConnection());
urlConnection.setConnectTimeout(1500);
urlConnection.setRequestMethod("POST");
urlConnection.setDoInput(true);
urlConnection.setDoOutput(true);
List<NameValuePair> params = new ArrayList<NameValuePair>();
params.add(new BasicNameValuePair("uname", uname));
params.add(new BasicNameValuePair("pass", password));
params.add(new BasicNameValuePair("email", email));
OutputStream os = urlConnection.getOutputStream();
BufferedWriter writer = new BufferedWriter(
new OutputStreamWriter(os, "UTF-8"));
writer.write(getQuery(params));
writer.flush();
writer.close();
os.close();
urlConnection.connect();
if(urlConnection.getResponseCode() == 200){
InputStream inputStream = new BufferedInputStream(urlConnection.getInputStream());
BufferedReader streamReader = new BufferedReader(new InputStreamReader(inputStream, "UTF-8"));
StringBuilder responseStrBuilder = new StringBuilder();
String inputStr;
while ((inputStr = streamReader.readLine()) != null)
responseStrBuilder.append(inputStr);
JSONObject json = new JSONObject(responseStrBuilder.toString());
String message = json.getString("message");
}

Sending post request to a php from google app engine

I have some servlets in GAE, called from an Android app; and I want to send a POST request from one of these servlets to a php hosted in localhost using xampp. The servlet reaches an IOException when trying to read the response.
This is the code of a the sample servlet i am using:
protected void doPost(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
String result = "";
try {
URL url = new URL("http://172.25.3.50:80/tempofinito/prueba.php");
HttpURLConnection con = (HttpURLConnection) url.openConnection();
con.setRequestMethod("POST");
con.setDoOutput(true);
con.setDoInput(true);
// Send
DataOutputStream wr = new DataOutputStream (
con.getOutputStream ());
wr.writeBytes ("prueba=" + URLEncoder.encode("message","UTF-8"));
wr.flush ();
wr.close ();
// Response
InputStream is = con.getInputStream();
BufferedReader rd = new BufferedReader(new InputStreamReader(is));
String line;
StringBuffer resp = new StringBuffer();
while((line = rd.readLine()) != null) {
resp.append(line);
resp.append('\r');
}
rd.close();
result = resp.toString();
} catch (MalformedURLException e) {
result = "malformed";
} catch (IOException e) {
result = "ioexception";
}
// Sends result to Android APP
PrintWriter out = response.getWriter();
out.println(result);
}
This is the php file:
<?php
$variable = $_POST["prueba"];
echo "ESTO ES UNA PRUEBA ".$variable;
?>
And this is the Android code:
new AsyncTask<Void, Void, String>() {
protected String doInBackground(Void... params) {
HttpClient client = new DefaultHttpClient();
HttpPost postMethod = new HttpPost(Globals.serverURL + "/prueba");
String result = "";
try {
// Ignore this ->
ArrayList<NameValuePair> nameValuePairs = new ArrayList<NameValuePair>(3);
nameValuePairs.add(new BasicNameValuePair("UserName", Globals.user));
nameValuePairs.add(new BasicNameValuePair("Pass", Globals.encrypt(Globals.pass)));
nameValuePairs.add(new BasicNameValuePair("Mode", "user"));
// <-
postMethod.setEntity(new UrlEncodedFormEntity(nameValuePairs));
HttpResponse response = client.execute(postMethod);
HttpEntity entity = response.getEntity();
result = EntityUtils.toString(entity);
} catch (ClientProtocolException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
return result;
}
So, the APP calls the servlet "prueba". This servlet just tries to send a POST request to the php file, but reaches an IOException in the "//Response" part. I suppose I'm doing something wrong because if I copy the same code from the servlet and paste it in the Android APP, instead of the code above, it works fine.
Should I do it in a different way inside Google App Engine?
It was a stupid problem with the firewall, which was blocking the connection.

Send an HttpPost request from Android, read Post from PHP

As I'm progressing through my Android learning in some spare time, I've encountered a strange behaviour of HttpPost request.
What I'm trying to achieve:
Make a simple POST request from Android application to Apache web-server running on my development PC and display the POSTed data from PHP script to which the form is sent.
My Android app's Java code resides inside an Activity as an AsyncTask as following:
private class DoSampleHttpPostRequest extends AsyncTask<Void, Void, CharSequence> {
#Override
protected CharSequence doInBackground(Void... params) {
BufferedReader in = null;
String baseUrl = "http://10.0.2.2:8080/android";
try {
HttpClient httpClient = new DefaultHttpClient();
HttpPost request = new HttpPost(baseUrl);
List<NameValuePair> postParameters = new ArrayList<NameValuePair>();
postParameters.add(new BasicNameValuePair("login", "someuser"));
postParameters.add(new BasicNameValuePair("data", "somedata"));
UrlEncodedFormEntity form = new UrlEncodedFormEntity(postParameters);
request.setEntity(form);
Log.v("log", "making POST request to: " + baseUrl);
HttpResponse response = httpClient.execute(request);
in = new BufferedReader(new InputStreamReader(response.getEntity().getContent()));
StringBuffer sb = new StringBuffer("");
String line = "";
String NL = System.getProperty("line.separator");
while ((line = in.readLine()) != null) {
sb.append(line + NL);
}
in.close();
return sb.toString();
} catch (Exception e) {
return "Exception happened: " + e.getMessage();
} finally {
if (in != null) {
try {
in.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
}
#Override
protected void onPostExecute(CharSequence result) {
// this refers to a TextView defined as a private field in the parent Activity
textView.setText(result);
}
}
My PHP code is the following:
<?php
echo "Hello<br />";
var_dump($_SERVER);
if ($_SERVER["REQUEST_METHOD"] == "POST") {
echo "Page was posted:<br />";
foreach($_POST as $key=>$var) {
echo "[$key] => $var<br />";
}
}
?>
And finally the problem:
As you can see, the $_SERVER contents is dumped, and in the output $_SERVER["REQUEST_METHOD"] has value GET despite the fact that I was actually making a POST request. Even if I try to dump the contents of $_POST, it's empty.
What am I doing wrong? Thanks in advance.
You might need to specify a trailing slash at the end of the URL.
Often Apache redirects requests that don't end in trailing slashes so that they do contain a trailing slash. That redirect is a GET redirect (without some tweaking), so all POST data is lost.

Categories

Resources