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.
Related
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);
}
I have a json array prepared for send to a php server. When I tried to send it by GET method it tells the URL is too long. So I decided to send it by POST. I would like to know is there any way to do it successfully?
As you give no details about any library you use, this is somehow vage. But you could have a look at http://www.mkyong.com/webservices/jax-rs/restful-java-client-with-jersey-client/ under point 3. to see how this can be achieved.
i used this code to send my json string
private class HttpAsyncTask extends AsyncTask<String, Void, String> {
#Override
protected String doInBackground(String... urls) {
return POST(urls[0]);
}
// onPostExecute displays the results of the AsyncTask.
#Override
protected void onPostExecute(String result) {
Toast.makeText(getBaseContext(), "Data Sent!", Toast.LENGTH_LONG).show();
}
}
public static String POST(String url){
InputStream inputStream = null;
String result = "";
try {
// 1. create HttpClient
HttpClient httpclient = new DefaultHttpClient();
// 2. make POST request to the given URL
HttpPost httpPost = new HttpPost(url);
String json = "what ever your string is";
// 5. set json to StringEntity
StringEntity se = new StringEntity(json);
// 6. set httpPost Entity
httpPost.setEntity(se);
// 7. Set some headers to inform server about the type of the content
httpPost.setHeader("Accept", "application/json");
httpPost.setHeader("Content-type", "application/json");
// 8. Execute POST request to the given URL
HttpResponse httpResponse = httpclient.execute(httpPost);
// 9. receive response as inputStream
inputStream = httpResponse.getEntity().getContent();
// 10. convert inputstream to string
if(inputStream != null)
result = convertInputStreamToString(inputStream);
else
result = "Did not work!";
} catch (Exception e) {
Log.d("InputStream", e.getLocalizedMessage());
}
// 11. return result
return result;
}
private static String convertInputStreamToString(InputStream inputStream) throws IOException
{
// TODO Auto-generated method stub
BufferedReader bufferedReader = new BufferedReader( new InputStreamReader(inputStream));
String line = "";
String result = "";
while((line = bufferedReader.readLine()) != null)
result += line;
inputStream.close();
return result;
}
}
use this to execute request
new HttpAsyncTask().execute("your URL");
I have noticed that my http requests tend to take alot of time compared apps communicating with same server. It makes my app feel sluggish and I was wondering if there is a better way of making these requests and updating the UI.
At the moment I use this method to make post requests
public String postRequest(List<NameValuePair> nameValuePairs, String method_name) {
String result = "";
HttpClient httpclient = new DefaultHttpClient();
HttpPost httppost = new HttpPost("http://www.mysite.com/api/"+method_name);
httppost.setHeader("Accept", "application/json");
httppost.setHeader("Authorization", "Basic somestuff");
try {
// Add your data
httppost.setEntity(new UrlEncodedFormEntity(nameValuePairs));
// Execute HTTP Post Request
HttpResponse response = httpclient.execute(httppost);
BufferedReader rd = new BufferedReader(new InputStreamReader(
response.getEntity().getContent()));
result = rd.readLine();
return result;
} catch (ClientProtocolException e) {
} catch (IOException e) {
}
return null;
}
And in my UI thread (i.e my Fragment classes) I use this in an Async Task like this
class MakeRequest extends AsyncTask<Integer, Integer, String> {
protected String doInBackground(Integer... counter) {
String result = "";
String method_name = "";
try {
List<NameValuePair> nameValuePairs = new ArrayList<NameValuePair>(2);
nameValuePairs.add(new BasicNameValuePair("id", value));
nameValuePairs.add(new BasicNameValuePair("name", name));
method_name = "petition/setPetition";
result = fixr.postRequest(nameValuePairs, method_name);
JSONObject jsonFile = new JSONObject(result);
if(!jsonFile.has("error")){
//Parse JSON using GSON
return "success";
}else{
return jsonFile.getString("error");
}
} catch (Exception e) {
e.printStackTrace();
}
return null;
}
protected void onPostExecute(String jsonResult) {
try {
if(jsonResult != null){
//update UI
}else{
//Error message
}
} catch (Exception e) {
e.printStackTrace();
}
}
}
I'd like to optimize this so users can have a really smooth experience on my application. I'm open to using third party http libraries or is there also an argument against using AysncTasks and maybe the runOnUiThread() instead.
Volley Library is better, http, https etc.
https://developers.google.com/live/shows/474338138
very mini sample here:https://github.com/ogrebgr/android_volley_examples/blob/master/src/com/github/volley_examples/Act_SimpleRequest.java
Try Volley mate! I changed from AsyncTasks to Volley library and i am pretty pleased from the overall experience!
Volley Library
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.
This question already has answers here:
How can I fix 'android.os.NetworkOnMainThreadException'?
(66 answers)
Closed 9 years ago.
This is the code I have so far.
public void postData(String toPost) {
// Create a new HttpClient and Post Header
HttpClient httpclient = new DefaultHttpClient();
HttpPost httppost = new HttpPost("http://www.mywebsite.com/dev/reverser.php");
//This is the data to send
String MyName = toPost; //any data to send
try {
// Add your data
List<NameValuePair> nameValuePairs = new ArrayList<NameValuePair>(1);
nameValuePairs.add(new BasicNameValuePair("action", MyName));
httppost.setEntity(new UrlEncodedFormEntity(nameValuePairs));
// Execute HTTP Post Request
ResponseHandler<String> responseHandler = new BasicResponseHandler();
String response = httpclient.execute(httppost, responseHandler);
//This is the response from a php application
String reverseString = response;
Toast.makeText(this, "response" + reverseString, Toast.LENGTH_LONG).show();
} catch (ClientProtocolException e) {
Toast.makeText(this, "CPE response " + e.toString(), Toast.LENGTH_LONG).show();
// TODO Auto-generated catch block
} catch (IOException e) {
Toast.makeText(this, "IOE response " + e.toString(), Toast.LENGTH_LONG).show();
// TODO Auto-generated catch block
}
}//end postData()
Can somebody please tell me what is wrong in the following code! I have established that there is a problem in the try catch block only and not anywhere else in the activity. I just do not know what it is or how to correct it.
My PHP code is quite simple. It is something like this -
//code to reverse the string
$reversed = strrev($_POST["action"]);
echo $reversed;
In a comment above you indicated that you are getting a android.os.NetworkOnMainThreadException.
In the most recent versions of Android you are not allowed to do networking on the main thread as it makes the UI unresponsive. Move your code to a different thread using AsyncTask (see the Android developer guide for details) or some other mechanism.
Adding as a seperate answer as the poster requests to do so .
Assumption :
a ) There is a text box that accepts the URL to load
b ) A button which when clicked performs the networking operation on the URL fetched f
Implement a button click listener that calls the following function :
private void URL()
{
String url = txtURL.getText().toString();
new URLTask().execute(new String[] { url });
}
private class URLTask extends AsyncTask<String, Void, String>
{
protected String doInBackground(String... urls)
{
BufferedReader br = null;
String url = urls[0];
StringBuffer sb = new StringBuffer("");
try
{
HttpClient client = new DefaultHttpClient();
HttpPost request = new HttpPost();
request.setURI(new URI(url));
List<NameValuePair> postParameters = new ArrayList<NameValuePair>();
postParameters.add(new BasicNameValuePair("param1", "value of param1"));
UrlEncodedFormEntity formEntity = new UrlEncodedFormEntity(postParameters);
request.setEntity(formEntity);
HttpResponse response = client.execute(request);
String line;
br = new BufferedReader(new InputStreamReader(response.getEntity().getContent()));
while ((line = br.readLine()) != null)
{
sb.append(line + "\n");
}
br.close();
}
catch(Exception e)
{
Toast.makeText(HttpPostActivity.this, "Exception: " + e.toString(), Toast.LENGTH_LONG).show();
}
finally
{
if (br != null)
{
try
{
br.close();
}
catch(IOException ioe)
{
ioe.printStackTrace();
}
}
}
return(sb.toString());
}
protected void onPostExecute(String result)
{
txtContent.setText(result);
}
You need to implement onPostExecute as well . There are other APIS .
Android Async Task Documentation
Try printing out the exception .
Use this code to print out your response . Check the status of the response
HttpResponse response = client.execute(request);
String line;
br = new BufferedReader(new InputStreamReader(response.getEntity().getContent()));
while ((line = br.readLine()) != null)
{
sb.append(line + "\n");
}
br.close();
}
catch(Exception e)
{
Toast.makeText(HttpPostActivity.this, "Exception: " + e.toString(), Toast.LENGTH_LONG).show();
}
Tell us the exception . It would be easy to pinpoint your problems then .
EDIT : ANSWER :
You are trying to perform a networking operation on the MAIN thread . This is an illegal thing to do . Create a AsyncTask i.e create a seperate thread to do your networking operations .
Android Details of the exception
Stackoverflow question