无法在android中执行POST方法

时间:2015-12-03 07:54:28

标签: android http-post

public class MainActivity extends ActionBarActivity implements View.OnClickListener{

    public static int flag;
    public boolean t;
    TextView view;
    Button button;
    private static final String DEBUG_TAG = "HttpExample";


    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.layout);
        view=(TextView)findViewById(R.id.textvi);
        button=(Button)findViewById(R.id.button);
        button.setOnClickListener(this);

    }


    @Override
    public void onClick(View v) {
        if(v.getId()==R.id.button){
            String stringUrl="http://mohdgadi.netai.net/Register.php";
            new DownloadWebpageTask().execute(stringUrl);
        }

    }
    private class DownloadWebpageTask extends AsyncTask<String, Void, String> {
        @Override
        protected String doInBackground(String... urls) {

            // params comes from the execute() call: params[0] is the url.
            try {
                return downloadUrl(urls[0]);
            } catch (IOException e) {
                return "Unable to retrieve web page. URL may be invalid.";
            }
        }
        // onPostExecute displays the results of the AsyncTask.
        @Override
        protected void onPostExecute(String result) {
            view.setText(result);
        }
    }

    private String downloadUrl(String myurl) throws IOException {
        InputStream is = null;
        String username="mohammed";
        String password="pass";
        int age=3;
        // Only display the first 500 characters of the retrieved
        // web page content.
        int len = 500;

        try {
            URL url = new URL(myurl);
            HttpURLConnection conn = (HttpURLConnection) url.openConnection();
            conn.setReadTimeout(10000 /* milliseconds */);
            conn.setConnectTimeout(15000 /* milliseconds */);
            conn.setRequestMethod("POST");
            conn.setDoInput(true);
            conn.setDoOutput(true);
            // Starts the query

            int response = conn.getResponseCode();
            Log.d(DEBUG_TAG, "The response is: " + response);
            ArrayList<NameValuePair> dataToSend = new ArrayList<>();
            dataToSend.add(new BasicNameValuePair("username", username));
            dataToSend.add(new BasicNameValuePair("password",password));
            dataToSend.add(new BasicNameValuePair("age", age + ""));
            OutputStream os = conn.getOutputStream();
            BufferedWriter writer = new BufferedWriter(
                    new OutputStreamWriter(os, "UTF-8"));
            writer.write(getQuery(dataToSend));
            writer.flush();
            writer.close();
            os.close();



            conn.connect();
            String result="done";
           // is = conn.getInputStream();

            // Convert the InputStream into a string
           // String contentAsString = readIt(is, len);
            //return contentAsString;
            return null;

            // Makes sure that the InputStream is closed after the app is
            // finished using it.
        } finally {
            if (is != null) {
                is.close();
            }
        }


    }
    private String getQuery(List<NameValuePair> params) throws UnsupportedEncodingException
    {
        StringBuilder result = new StringBuilder();
        boolean first = true;

        for (NameValuePair pair : params)
        {
            if (first)
                first = false;
            else
                result.append("&");

            result.append(URLEncoder.encode(pair.getName(), "UTF-8"));
            result.append("=");
            result.append(URLEncoder.encode(pair.getValue(), "UTF-8"));
        }

        return result.toString();
    }

我尝试在我的网站上发布数据但是当我按下它不更新我的网站和数据库的按钮时它似乎工作。 我评论了它在GET方法中完全正常工作的输入流代码但是,post不起作用,甚至我的数据库也没有得到更新。

这是我在名为Register.php的公共文件夹中的php文件

<?php
    $con=mysqli_connect("mysql13.000webhost.com","a3039721_admin","123456ha","a3039721_databas");

    $data="";
    if(isset($age,$username,$password)){
    $age = $_POST["age"];
    $username = $_POST["username"];
    $password = $_POST["password"];
    $data=$age.$username.$password;
    }
    echo $data;

    $age = $_POST["age"];
    $username = $_POST["username"];
    $password = $_POST["password"];
    $statement = mysqli_prepare($con, "INSERT INTO users ( age, username, password) VALUES (?, ?, ?)");
    mysqli_stmt_bind_param($statement, "iss", $age, $username, $password);
    mysqli_stmt_execute($statement);

    mysqli_stmt_close($statement);

    mysqli_close($con);*/
?>

2 个答案:

答案 0 :(得分:0)

int response = conn.getResponseCode();

您在编写发布数据之前尝试获取响应代码。在

之后检索响应代码
conn.connect();

答案 1 :(得分:0)

要发布帖子请求,您可以使用以下代码:

public void postRequest() {
// Create a new HttpClient and Post Header
HttpClient httpclient = new DefaultHttpClient();
HttpPost httppost = new HttpPost("<Enter url here>");

try {
    // Add your data
    List<NameValuePair> nameValuePairs = new ArrayList<NameValuePair>(2);
    nameValuePairs.add(new BasicNameValuePair("Name", "StackOverFlow"));
    nameValuePairs.add(new BasicNameValuePair("Date", "4th December"));
    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
}
}

有关完整教程和说明,请点击here