发送POST请求

时间:2018-06-05 14:14:10

标签: java android

我正在尝试使用来自2个edittext字段的数据向php文件发出请求。但它没有用。 php文件是可访问和工作的。 Any1可以帮到我吗?

public class AddInfo extends Activity {

private EditText etxt1, etxt2;
private String result, code, omschrijving;
@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_add_info);
    etxt1 = (EditText) findViewById(R.id.etext1);
    etxt2 = (EditText) findViewById(R.id.etext2);
    result = getIntent().getStringExtra("message_key");
    etxt1.setText(result);
}

public void saveInfo (View view)
{
    code = etxt1.getText().toString();
    omschrijving = etxt2.getText().toString();
    BackgroundTask backgroundTask = new BackgroundTask();
    backgroundTask.execute(code,omschrijving);
    finish();

}

class BackgroundTask extends AsyncTask<String,Void,String>
{
    String add_info_url;
    @Override
    protected  void  onPreExecute() {
        add_info_url = "192.168.0.41/add_info.php";
    }

    @Override
    protected String doInBackground(String... args) {
        String code,omschrijving;
        code = args[0];
        omschrijving = args[1];
        try {

            URL url = new URL(add_info_url);
            HttpURLConnection httpURLConnection = (HttpURLConnection) url.openConnection();
            httpURLConnection.setRequestMethod("POST");
            httpURLConnection.setDoOutput(true);
            OutputStream outputStream = httpURLConnection.getOutputStream();
            BufferedWriter bufferedWriter = new BufferedWriter(new OutputStreamWriter(outputStream,"UTF-8"));
            String data_string = URLEncoder.encode("code","UTF-8")+"="+URLEncoder.encode(code, "UTF-8")+"&"+
                    URLEncoder.encode("omschrijving","UTF-8")+"="+URLEncoder.encode(omschrijving, "UTF-8");
            bufferedWriter.write(data_string);
            bufferedWriter.flush();
            bufferedWriter.close();
            outputStream.close();
            InputStream inputStream = httpURLConnection.getInputStream();
            inputStream.close();
            httpURLConnection.disconnect();
            return "Row added";

        } catch (MalformedURLException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        }
        return null;
    }

    @Override
    protected void  onProgressUpdate(Void... values){
        super.onProgressUpdate(values);
    }

    @Override
    protected  void onPostExecute(String resultt){
        Toast.makeText(getApplicationContext(),resultt,Toast.LENGTH_LONG).show();

    }
}
}

Toast还应该显示添加的行,但它只是空的。

仅为了记录,我添加了权限。

android.permission.INTERNET对&#34;

android.permission.ACCESS_NETWORK_STATE&#34;

1 个答案:

答案 0 :(得分:0)

Greenapps为我解决了这个问题。我忘记了我的网址前面的协议(http://)

add_info_url =“192.168.0.41/add_info.php”;。你忘记了协议。 add_info_url =“http://192.168.0.41/add_info.php”;