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
Related
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.
This question already has answers here:
Android, Java: HTTP POST Request
(8 answers)
Closed 7 years ago.
I am doing a post request in Android. It should give me a response in the form of a string. Thats what i do to check it. However it gives me an empty string back. It's in the toast message. Am i doing something wrong, any hints for me guys?
private void makePostRequest() throws UnsupportedEncodingException {
SharedPreferences postpreference = this.getSharedPreferences("preferences", MODE_PRIVATE);
String password = postpreference.getString("Password", null);
String username = postpreference.getString("Username", null);
String data = URLEncoder.encode("username", "UTF-8") + "=" + URLEncoder.encode(username, "UTF-8");
data += "&" + URLEncoder.encode("password", "UTF-8") + "=" + URLEncoder.encode(password, "UTF-8");
String text = "";
BufferedReader reader = null;
try {
// send post data request
URL url = new URL("secreturl but working");
URLConnection conn = url.openConnection();
OutputStreamWriter streamWriter = new OutputStreamWriter(conn.getOutputStream());
streamWriter.write(data);
streamWriter.flush();
//read the response
reader = new BufferedReader(new InputStreamReader(conn.getInputStream()));
StringBuilder sb = new StringBuilder();
String line = null;
while ((line = reader.readLine()) != null) {
// Append server response in string
sb.append(line + "\n");
}
text = sb.toString();
} catch (Exception ex) {
} finally {
try {
reader.close();
} catch (Exception e) {
}
}
// Show response on activity
Toast.makeText(getApplicationContext(), text, Toast.LENGTH_LONG).show();
}
Check for response code. Then only get the response if you are getting the correct response code.
int responseCode = conn.getResponseCode();
I fixed it following the first solution in this link : Android, Java: HTTP POST Request
Thanks for help
Edit : Correct way to do the post request.
HttpClient httpclient = new DefaultHttpClient();
HttpPost httppost = new HttpPost("http://www.yoursite.com/script.php");
try {
// Add your data
List<NameValuePair> nameValuePairs = new ArrayList<NameValuePair>(2);
nameValuePairs.add(new BasicNameValuePair("id", "12345"));
nameValuePairs.add(new BasicNameValuePair("stringdata", "AndDev is Cool!"));
httppost.setEntity(new UrlEncodedFormEntity(nameValuePairs));
// Execute HTTP Post Request
HttpResponse response = httpclient.execute(httppost);
} catch (ClientProtocolException e) {
// TODO Auto-generated catch block
} catch (IOException e) {
// TODO Auto-generated catch block
}
I have a for loop running in the background, and it's uploading an array to my database online. However, it only uploads the first time it goes through, and I can't figure out why.
I can follow the code as it loops through the params.add and the upload, but when I look at my database, only one extra item is added each time. My success int is also set to 0 each time but the first one.
I've looked at similar problems, and tried to fix this, but I can't find anything. I'd appreciate any help on this.
This is the relevant code ( I call it with "new SavePotholeDetails().execute();" ):
protected void onPreExecute() {
super.onPreExecute();
pDialog = new ProgressDialog(SensorActivity.this);
pDialog.setMessage("Loading pothole details. Please wait...");
pDialog.setIndeterminate(false);
pDialog.setCancelable(true);
pDialog.show();
}
/**
* Saving product
* */
protected String doInBackground(String... args) {
// TODO: Get data from sensorData
for (int i = 0; i < sensorData.size(); i++) {
// Building Parameters
List<NameValuePair> params = new ArrayList<NameValuePair>();
params.add(new BasicNameValuePair(TAG_TIME, Long.toString(sensorData.get(i).getTimestamp())));
params.add(new BasicNameValuePair(TAG_ACCEL_X, Double.toString(sensorData.get(i).getX())));
params.add(new BasicNameValuePair(TAG_ACCEL_Y, Double.toString(sensorData.get(i).getY())));
params.add(new BasicNameValuePair(TAG_ACCEL_Z, Double.toString(sensorData.get(i).getZ())));
params.add(new BasicNameValuePair(TAG_CLIENT_ID, "Epidilius")); //TODO: Make a client ID variable
params.add(new BasicNameValuePair(TAG_GPS_X, Double.toString(sensorData.get(i).getLat())));
params.add(new BasicNameValuePair(TAG_GPS_Y, Double.toString(sensorData.get(i).getLng())));
// sending modified data through http request
// Notice that update product url accepts POST method
JSONObject json = jsonParser.makeHttpRequest(
url_update_pothole, "POST", params);
// check json success tag
try {
int success = json.getInt(TAG_SUCCESS);
if (success == 1) {
// successfully updated
Intent intent = getIntent();
// send result code 100 to notify about product update
setResult(100, intent);
finish();
} else {
// failed to update product
}
} catch (JSONException e) {
e.printStackTrace();
}
}
return null;
}
protected void onPostExecute(String file_url) {
// dismiss the dialog once product updated
pDialog.dismiss();
}
EDIT:
Here is the JSONParser class:
public class JSONParser {
static InputStream is = null;
static JSONObject jObj = null;
static String json = "";
// constructor
public JSONParser() {
}
// function get json from url
// by making HTTP POST or GET mehtod
public JSONObject makeHttpRequest(String url, String method,
List<NameValuePair> params) {
// Making HTTP request
try {
// check for request method
if(method == "POST"){
// request method is POST
// defaultHttpClient
DefaultHttpClient httpClient = new DefaultHttpClient();
HttpPost httpPost = new HttpPost(url);
httpPost.setEntity(new UrlEncodedFormEntity(params));
HttpResponse httpResponse = httpClient.execute(httpPost);
HttpEntity httpEntity = httpResponse.getEntity();
is = httpEntity.getContent();
}else if(method == "GET"){
// request method is GET
DefaultHttpClient httpClient = new DefaultHttpClient();
String paramString = URLEncodedUtils.format(params, "utf-8");
url += "?" + paramString;
HttpGet httpGet = new HttpGet(url);
HttpResponse httpResponse = httpClient.execute(httpGet);
HttpEntity httpEntity = httpResponse.getEntity();
is = httpEntity.getContent();
}
} catch (UnsupportedEncodingException e) {
e.printStackTrace();
} catch (ClientProtocolException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
try {
BufferedReader reader = new BufferedReader(new InputStreamReader(
is, "UTF-8"), 8);
StringBuilder sb = new StringBuilder();
String line = null;
while ((line = reader.readLine()) != null) {
sb.append(line + "\n");
}
is.close();
json = sb.toString();
} catch (Exception e) {
Log.e("Buffer Error", "Error converting result " + e.toString());
}
// try parse the string to a JSON object
try {
jObj = new JSONObject(json);
} catch (JSONException e) {
Log.e("JSON Parser", "Error parsing data " + e.toString());
}
// return JSON String
return jObj;
}
}
If you're just running a simple loop and not blocking the loop while your AsyncTasks are executing, then they're just getting fired all at once. I also see that you're sending your web requests through the jsonParser object, but I don't know what that is. If this object is shared between AsyncRequest instances (for example, if all of this stuff is scoped within a single Activity) or if the implementation blocks so that only one request can go out at a time, then everything after the first iteration of the loop is going to fail because your HTTP client is busy.
Without posting more than your AsyncTask code, I can't help much further than that. You might want to think more about how you're executing your loop. You could do something where the loop waits for each AsyncTask instance to call back (from the onPostExecute method) to signal that it's finished. Or, you can do the looping inside of a single AsyncTask instance (probably a more lightweight solution as only a single thread is created).
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.
I want to post String data over HttpClient in android
but i'm tired after receive response status code 503 - service unavailable and
return response as Html code for our url.
I write in the following Code in JAVA Application and i return the data but when I write the same code in Android Application i receive an exception file I/O not found, I'm Puzzled for this case:
public void goButton(View v)
{
try{
URL url = new URL("https://xxxxxxxxx");
HttpURLConnection conn = (HttpURLConnection) url.openConnection();
Test ts= new ApiRequest("null","getUserbyID",new String[] { "66868706" });
String payLoad = ts.toString(); //toSting is override method that create //JSON Object
System.out.println("--->>> " + payLoad);
conn.setDoOutput(true);
OutputStreamWriter wr = new OutputStreamWriter(conn.getOutputStream());
System.out.println("=================>>> "+ payLoad);
wr.write(payLoad);
wr.flush();
BufferedReader rd = new BufferedReader(new nputStreamReader(conn.getInputStream()));
String line;
while ((line = rd.readLine()) != null) {
System.out.println("-->> " + line);
response += line;
}
wr.close();
rd.close();
System.out.println("=================>>> "+ response);
} catch (Exception e) {
e.printStackTrace();
System.out.println("=================>>> " + e.toString());
throw new RuntimeException(e);
}
I try to put this code in AsynTask, Thread but i receive the same response status code.
I write in the following Android code as an example data
public void goButton(View v)
{
try{
new Thread(new Runnable() {
public void run() {
HttpClient client = new DefaultHttpClient();
HttpConnectionParams.setConnectionTimeout(client.getParams(),
10000); // Timeout Limit
HttpResponse response;
String url = "https://xxxxxxxxxxxxx";
JSONObject json = new JSONObject();
try {
HttpPost post = new HttpPost(url);
post.setHeader("Content-type", "application/json");
json.put("service","null");
json.put("method", getUserByID.toString());
json.put("parameters", "1111");
System.out.println(">>>>>>>>>>>" + json.toString());
StringEntity se = new StringEntity(json.toString());
se.setContentType(new BasicHeader(HTTP.CONTENT_TYPE,
"application/json"));
post.setEntity(se);
String response = client.execute(post);
if (response != null) {
String temp = EntityUtils.toString(response.getEntity());
System.out.println(">>>>>>>>>>>" + temp);
}
} catch (Exception e) {
e.printStackTrace();
System.out.println(">>>>>>>>>>>" + e.getMessage());
}
}
}).start();
}
Please Help me to find solution for this problem :(
Thank you in advance
Here is an code snippet , hoping it will help you.
1)An function which carries the http get service
private String SendDataFromAndroidDevice() {
String result = "";
try {
HttpClient httpclient = new DefaultHttpClient();
HttpGet getMethod = new HttpGet("your url + data appended");
BufferedReader in = null;
BasicHttpResponse httpResponse = (BasicHttpResponse) httpclient
.execute(getMethod);
in = new BufferedReader(new InputStreamReader(httpResponse
.getEntity().getContent()));
StringBuffer sb = new StringBuffer("");
String line = "";
while ((line = in.readLine()) != null) {
sb.append(line);
}
in.close();
result = sb.toString();
} catch (Exception e) {
e.printStackTrace();
}
return result;
}
2) An Class which extends AsyncTask
private class HTTPdemo extends
AsyncTask<String, Void, String> {
#Override
protected void onPreExecute() {}
#Override
protected String doInBackground(String... params) {
String result = SendDataFromAndroidDevice();
return result;
}
#Override
protected void onProgressUpdate(Void... values) {}
#Override
protected void onPostExecute(String result) {
if (result != null && !result.equals("")) {
try {
JSONObject resObject = new JSONObject(result);
} catch (Exception e) {
e.printStackTrace();
}
}
}
}
3) Inside your onCreate method
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView("your layout");
if ("check here where network/internet is avaliable") {
new HTTPdemo().execute("");
}
}
This code snippet ,
Android device will send the data via URL towards Server
now server needs to fetch that data from the URL
Hey Mohammed Saleem
The code snippet provided by me works in the following way,
1)Android device send the URL+data to server
2)Server [say ASP.NET platform used] receive the data and gives an acknowledgement
Now the Code which should be written at client side (Android) is provided to you, the later part of receiving that data at server is
Server needs to receive the data
An webservice should be used to do that
Implement an webservice at server side
The webservice will be invoked whenever android will push the URL+data
Once you have the data ,manipulated it as you want