Post request to server using HttpUrlConnection

后端 未结 1 1067
陌清茗
陌清茗 2021-01-20 18:02

I am stuck in between. I want to implement a POST method using HttpUrlConnection to Post the email,name and password for registering a user to the server. Here is my code :

1条回答
  •  囚心锁ツ
    2021-01-20 18:14

    Try something like this:

    try {
        url = new URL(params[0]);
        httpURLConnection = (HttpURLConnection) url.openConnection();
        httpURLConnection.setDoInput(true);
        httpURLConnection.setDoOutput(true);
        httpURLConnection.setRequestMethod("POST");
    
    
    
        outputStream = httpURLConnection.getOutputStream();
    
        bufferedWriter = new BufferedWriter(new OutputStreamWriter(outputStream));
        bufferedWriter.write(myValues);
        bufferedWriter.flush();
    
        int statusCode = httpURLConnection.getResponseCode();
        Log.d(Constants.LOG_TAG, " The status code is " + statusCode);
    
        if (statusCode == 200) {
            inputStream = new BufferedInputStream(httpURLConnection.getInputStream());
            response = convertInputStreamToString(inputStream);
            Log.d(Constants.LOG_TAG, "The response is " + response);
    
            JSONObject jsonObject = new JSONObject(response);
    
    return true;
    
        } else {
            return false;
        }
    
    } catch (Exception e) {
    
        e.printStackTrace();
    } finally {
        try {
            if (inputStream != null) {
                inputStream.close();
            }
            if (outputStream != null) {
                outputStream.close();
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
    }
    

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