1

I am creating an app that takes user Input and saves this in a Text file on the server. I am having issues sending string data to the PHP file

In a previous app I used HttpClient to authenticate users against an SQL database.

After I had written this code, I then seen that HTTPClient is No longer supported.

What is the best way to send this string to a PHP file using a supported method?

Current code:

   package com.example.test.myapplication;
    import android.os.Bundle;
    import android.support.v7.app.AppCompatActivity;
    import android.widget.Button;
    import android.widget.EditText;
    import android.widget.TextView;
    import butterknife.Bind;
    import butterknife.ButterKnife;
    import butterknife.OnClick;
    import org.apache.http.NameValuePair;
    import org.apache.http.client.ClientProtocolException;
    import org.apache.http.client.HttpClient;
    import org.apache.http.client.entity.UrlEncodedFormEntity;
    import org.apache.http.client.methods.HttpPost;
    import org.apache.http.impl.client.DefaultHttpClient;
    import org.apache.http.message.BasicNameValuePair;

    public class MainActivity extends AppCompatActivity {

        @Bind(R.id.tvTitle)
        TextView title;
        @Bind(R.id.etName)
        EditText name;
        @Bind(R.id.etEmail)
        EditText email;
        @Bind(R.id.etIdea)
        EditText idea;
        @Bind(R.id.btnSubmit)
        Button submit;

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

        }
        /**
         * Method used to submit user data to PHP file
         *
         * @param button
         */
        @OnClick(R.id.btnSubmit)
        public void SubmitIdea(Button button) {

            //get input from editText boxes
            String  toSubmit = name.getText().toString() + " " + email.getText().toString() + " " + idea.getText().toString();

            HttpClient client=new DefaultHttpClient();
            HttpPost postMethod=new HttpPost("my ip/file.php");
           postMethod.setEntity(new UrlEncodedFormEntity(toSubmit,HTTP.UTF_8));
client.execute(getMethod);      


        }

    }
java12340000
  • 101
  • 1
  • 5

2 Answers2

0

HTTPClient is deprecated. You need to use URLConnection instead.

Mohammed Aouf Zouag
  • 17,042
  • 4
  • 41
  • 67
  • Do you have an example of how I could use this to send a string to a file on my server? Thanks! – java12340000 Nov 08 '15 at 21:59
  • Thanks for the link, however that is for inserting into a database, I am looking to POST the string to a php file then insert it into a text file. Can I still use this? Sorry my server side knowledge is very limited. – java12340000 Nov 08 '15 at 22:06
  • Also, this example is using HTTPClient? – java12340000 Nov 08 '15 at 22:11
0

Below is a sample code that should do it, it comes from larger code base. You can also try some wrapper classes like OKHttp.

To enable legacy HTTPClient API look here: How to add Apache HTTP API (legacy) as compile-time dependency to build.grade for Android M?.

  public static InputStream toInputStream(String input, String encoding) throws IOException {
    byte[] bytes = encoding != null ? input.getBytes(encoding) : input.getBytes();
    return new ByteArrayInputStream(bytes);
  }

  private static final int DEFAULT_BUFFER_SIZE = 1024 * 4;

  public static long copyLarge(InputStream input, OutputStream output)
          throws IOException {
    byte[] buffer = new byte[DEFAULT_BUFFER_SIZE];
    long count = 0;
    int n = 0;
    while (-1 != (n = input.read(buffer))) {
      output.write(buffer, 0, n);
      count += n;
    }
    return count;
  }  

  public static int copy(InputStream input, OutputStream output) throws IOException {
    long count = copyLarge(input, output);
    if (count > Integer.MAX_VALUE) {
      return -1;
    }
    return (int) count;
  }

  String getData(String postData) throws IOException {
    StringBuilder respData = new StringBuilder();
    URL url = new URL("my ip/file.php");
    URLConnection conn = url.openConnection();
    HttpURLConnection httpUrlConnection = (HttpURLConnection) conn;

    httpUrlConnection.setUseCaches(false);
    httpUrlConnection.setRequestProperty("User-Agent", "YourApp");
    httpUrlConnection.setConnectTimeout(30000);
    httpUrlConnection.setReadTimeout(30000);

    httpUrlConnection.setRequestMethod("POST");
    httpUrlConnection.setDoOutput(true);

    OutputStream os = httpUrlConnection.getOutputStream();
    InputStream postStream = toInputStream(postData, "UTF-8");
    try {
      copy(postStream, os);
    } finally {
      postStream.close();
      os.flush();
      os.close();
    }

    httpUrlConnection.connect();

    int responseCode = httpUrlConnection.getResponseCode();

    if (200 == responseCode) {
      InputStream is = httpUrlConnection.getInputStream();
      InputStreamReader isr = null;
      try {
        isr = new InputStreamReader(is);
        char[] buffer = new char[1024];
        int len;
        while ((len = isr.read(buffer)) != -1) {
          respData.append(buffer, 0, len);
        }
      } finally {
        if (isr != null)
          isr.close();
      }
      is.close();
    }
    else {
      // use below to get error stream 
      // inputStream = httpUrlConnection.getErrorStream();
    }
    return respData.toString();
  }
Community
  • 1
  • 1
marcinj
  • 48,511
  • 9
  • 79
  • 100
  • Thanks, From my exsiting code: How should I call the method to upload my string (toSubmit) ? – java12340000 Nov 08 '15 at 22:24
  • Sorry I have found out how to do it, thanks for the example code. If I just wanted to send that one string, what should my PHP file look like on the server? – java12340000 Nov 08 '15 at 22:31