将字符串发送到服务器上的PHP文件(HTTPClient不再支持)



我正在创建一个应用程序,它接受用户输入并将其保存在服务器上的Text文件中。我在将string数据发送到PHP文件时遇到问题

在以前的一个应用程序中,我使用HttpClient根据SQL数据库对用户进行身份验证。

在我写完这段代码之后,我发现HTTPClient不再受支持。

使用支持的方法将此字符串发送到PHP文件的最佳方式是什么?

当前代码:

   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);      

        }
    }

HTTPClient已弃用。您需要使用URLConnection相反

下面是一个应该这样做的示例代码,它来自更大的代码库。您也可以尝试一些包装类,如OKHttp。

要启用传统HTTPClient API,请看这里:如何将Apache HTTP API(传统)添加为Android M的build.grade的编译时间依赖项?。

  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();
  }

相关内容

  • 没有找到相关文章

最新更新