在Android上将请求发布到.php文件

时间:2019-06-06 09:46:54

标签: java php json http-post

我正在尝试从我的Android应用程序向.php文件发出POST请求,但是它不起作用。它应该将scannedData的值发送到我的.php脚本,但返回"false: 500"

有人知道为什么吗?由于它们已更改,因此您不能再使用httppost了,StackOverflow上的大多数答案已过时。

public class SendRequest extends AsyncTask<String, Void, String> {
    protected void onPreExecute(){}

    protected String doInBackground(String... arg0) {
        try{
            //Enter script URL Here
            URL url = new URL("https://example.com/code.php");
            JSONObject postDataParams = new JSONObject();

            //int i;
            //for(i=1;i<=70;i++)

            //    String usn = Integer.toString(i);

            //Passing scanned code as parameter
            postDataParams.put("sdata",scannedData);
            Log.e("params",postDataParams.toString());
            HttpURLConnection conn = (HttpURLConnection) url.openConnection();
            conn.setReadTimeout(15000 /* milliseconds */);
            conn.setConnectTimeout(15000 /* milliseconds */);
            conn.setRequestMethod("POST");
            conn.setDoInput(true);
            conn.setDoOutput(true);

            OutputStream os = conn.getOutputStream();
            BufferedWriter writer = new BufferedWriter(
                    new OutputStreamWriter(os, "UTF-8"));
            writer.write(getPostDataString(postDataParams));

            writer.flush();
            writer.close();
            os.close();

            int responseCode=conn.getResponseCode();

            if (responseCode == HttpsURLConnection.HTTP_OK) {

                BufferedReader in=new BufferedReader(new InputStreamReader(conn.getInputStream()));
                StringBuffer sb = new StringBuffer("");
                String line="";

                while((line = in.readLine()) != null) {
                    sb.append(line);
                    break;
                }

                in.close();
                return sb.toString();
            }
            else {
                return new String("false : "+responseCode);
            }
        }
        catch(Exception e){
            return new String("Exception: " + e.getMessage());
        }
    }

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

    }
}

public String getPostDataString(JSONObject params) throws Exception {
    StringBuilder result = new StringBuilder();
    boolean first = true;

    Iterator<String> itr = params.keys();

    while(itr.hasNext()){
        String key= itr.next();
        Object value = params.get(key);

        if (first)
            first = false;
        else
            result.append("&");

        result.append(URLEncoder.encode(key, "UTF-8"));
        result.append("=");
        result.append(URLEncoder.encode(value.toString(), "UTF-8"));
    }
    return result.toString();
}

0 个答案:

没有答案
相关问题