Android POST request not working

后端 未结 1 1139
眼角桃花
眼角桃花 2020-12-21 11:57

I am doing this:

@Override
protected Void doInBackground(String... strings) {

    try {
        String query = \"username=\" + strings[0] + \"&duration=         


        
相关标签:
1条回答
  • 2020-12-21 12:27

    hey try to use this syntax.

    @Override
    protected String doInBackground(String... params) {
    
        String urlString = params[0];
        String userName = params[1];
        String password = params[2];
        URL url = null;
        InputStream stream = null;
        HttpURLConnection urlConnection = null;
        try {
            url = new URL(urlString);
            urlConnection = (HttpURLConnection) url.openConnection();
            urlConnection.setRequestMethod("POST");
            urlConnection.setDoOutput(true);
    
            String data = URLEncoder.encode("userName", "UTF-8")
                    + "=" + URLEncoder.encode(userName, "UTF-8");
    
            data += "&" + URLEncoder.encode("password", "UTF-8") + "="
                    + URLEncoder.encode(password, "UTF-8");
    
            urlConnection.connect();
    
            OutputStreamWriter wr = new OutputStreamWriter(urlConnection.getOutputStream());
            wr.write(data);
            wr.flush();
    
            stream = urlConnection.getInputStream();
            BufferedReader reader = new BufferedReader(new InputStreamReader(stream, "UTF-8"), 8);
            String result = reader.readLine();
            return result;
    
        } catch (IOException e) {
            e.printStackTrace();
        } finally {
            if (urlConnection != null) {
                urlConnection.disconnect();
            }
        }
    
        try {
            Thread.sleep(2000);
        } catch (InterruptedException e) {
            e.printStackTrace();
            Log.i("Result", "SLEEP ERROR");
        }
        return null;
    }
    

    Hope this helps. :)

    0 讨论(0)
提交回复
热议问题