0

I have a server made in python that reads the querystring-message and stores it in a sqlite database, and then displays the content.

Now I want to send the message from a android application. This is my code so far.

import java.io.BufferedReader;
import java.io.InputStreamReader;
import java.io.OutputStreamWriter;
import java.io.UnsupportedEncodingException;
import java.net.URL;
import java.net.URLConnection;
import java.net.URLEncoder;

import android.R.string;
import android.os.Bundle;
import android.app.Activity;
import android.view.Menu;
import android.view.View;
import android.widget.Button;
import android.widget.TextView;

public class MainActivity extends Activity {

Button send;
TextView display;
String message;

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main);

    send = (Button)findViewById(R.id.button1);
    display = (TextView)findViewById(R.id.editText1);


    send.setOnClickListener(new View.OnClickListener() {

        @Override
        public void onClick(View v) {

            try{
                post();
            }
            catch(Exception e)
            {
                display.setText("Det sket sig");

            }

        }

        public void post() throws  UnsupportedEncodingException
        {
            message = display.getText().toString();
            String data = URLEncoder.encode("?message", "UTF-8") 
                    + "=" + URLEncoder.encode(message, "UTF-8");

            String text = "";
            BufferedReader reader=null;

            try
            {
                URL url = new URL("http:homepage.net");

                URLConnection conn = url.openConnection(); 
                conn.setDoOutput(true); 
                OutputStreamWriter wr = new OutputStreamWriter(conn.getOutputStream()); 
                wr.write(data); 
                wr.flush(); 

                reader = new BufferedReader(new InputStreamReader(conn.getInputStream()));
                StringBuilder sb = new StringBuilder();
                String line = null;

                while((line = reader.readLine()) != null)
                {
                       sb.append(line + "\n");
                }
                text = sb.toString();
            }
            catch(Exception e)
            {

            }
            finally
            {
                try
                {
                    reader.close();
                }

                catch(Exception ex) {}
            }
            display.setText(text);
        }
    });


}

@Override
public boolean onCreateOptionsMenu(Menu menu) {
    // Inflate the menu; this adds items to the action bar if it is present.
    getMenuInflater().inflate(R.menu.main, menu);
    return true;
}

}

This is not functioning as per the expectations. What am i doing wrong here?

5 Answers5

0

for network related operation you have to use asynctask or thread other wise you wil get NetworkOnMainThread Exception. refer here

private class MyTask extends AsyncTask<Void, Void, Void> { ... }
Nambi
  • 11,944
  • 3
  • 37
  • 49
0

Use following AsyncTask to make server request:

public class RestServiceTask extends AsyncTask<String, Void, String> {

    private String errorMessage;

    public RestServiceTask() {

    }

    @Override
    protected void onPreExecute() {
        super.onPreExecute();
    }

    @Override
    protected String doInBackground(String... params) {
        String url = params[1];
        String method = params[2];
        HttpParams httpParameters = new BasicHttpParams();
        HttpConnectionParams.setConnectionTimeout(httpParameters, 60000);
        HttpConnectionParams.setSoTimeout(httpParameters, 60000);
        HttpClient client = new DefaultHttpClient(httpParameters);

        HttpUriRequest request;
        try {

            if (method.equals("get")) {
                request = new HttpGet(url);
            } else {
                request = new HttpPost(url);

                if (params.length > 0 && params[0] != null) {
                    StringEntity entity = new StringEntity(params[0]);
                    ((HttpPost) request).setEntity(entity);
                    Crashlytics.log(Log.INFO, "Request", params[0]);
                }

                ((HttpPost) request).setHeader("Content-Type",
                        "application/json");
            }

            HttpResponse response = client.execute(request);
            HttpEntity entity = response.getEntity();

            String json = convertStreamToString(entity.getContent());
            Crashlytics.log(Log.INFO, "Response", json);
            return json;
        } catch (Exception e) {

        }
        return null;
    }

    @Override
    protected void onPostExecute(String result) {
        super.onPostExecute(result);
        //process your result 
    }

    public String convertStreamToString(InputStream is) throws IOException {
        if (is != null) {
            Writer writer = new StringWriter();

            char[] buffer = new char[1024];
            try {
                Reader reader = new BufferedReader(new InputStreamReader(is,
                        "UTF-8"));
                int n;
                while ((n = reader.read(buffer)) != -1) {
                    writer.write(buffer, 0, n);
                }
            } finally {
                is.close();
            }
            return writer.toString();
        } else {
            return "";
        }
    }
}

Use it by:

new RestServiceTask().execute("<json string>",url,method);//method can be get,post
vipul mittal
  • 17,343
  • 3
  • 41
  • 44
0

try this simple example if you have any doubt follow this links:

     HttpClient httpclient = new DefaultHttpClient();
     HttpPost httppost = new HttpPost("http://www.codeincloud.tk/First.php");
   try {
       HttpResponse response = httpclient.execute(httppost);
       final String str =  EntityUtils.toString(response.getEntity());
       TextView tv = (TextView) findViewById(R.id.textView1);
       tv.setText(str);
    } 
   catch (IOException e) {
       // TODO Auto-generated catch block
       e.printStackTrace();
    }

http://codeoncloud.blogspot.in/2012/07/android-php-web-service-client.html,http://sampleprogramz.com/android/singlewebservicecall.php

skyshine
  • 2,767
  • 7
  • 44
  • 84
0

You should change the title of your question, there is no such thing as queryString in a POST. Query String parameters only gets added in a GET, and in POST you pass data in the body of the request.

Also, you could use this in combination with AsyncTask to solve your problem

EDIT: Also, Check here for more about GET and POST

Community
  • 1
  • 1
Daniel Conde Marin
  • 7,588
  • 4
  • 35
  • 44
0

Try this :

HttpParams params = new BasicHttpParams();
params.setParameter(CoreProtocolPNames.PROTOCOL_VERSION, HttpVersion.HTTP_1_1);
HttpClient httpClient = new DefaultHttpClient(params);
HttpPost httpPost = new HttpPost(your website);

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("message", message1));
entityParams.add(new BasicNameValuePair("message2", message2));

httpPost.setEntity(new UrlEncodedFormEntity(entityParams, "utf-8"));

String resp = httpClient.execute(httpPost, new BasicResponseHandler());
Lockon
  • 1
  • 1