简体   繁体   中英

How to use HttpURLConnection to make oauth2 request

I am trying to make a practise using HttpURLConnection to make a Oauth2 request on Android Studio. However, when I tried my code on bluestacks, the app crashed, and I didn't find the error. Can anyone help me with this?

Here is my code:

package com.example.administrator.practise;

import android.os.Bundle;
import android.app.Activity;
import android.view.View;
import android.widget.Button;
import android.widget.TextView;
import java.io.IOException;
import java.net.HttpURLConnection;
import java.net.MalformedURLException;
import java.net.URL;

public class MainActivity extends Activity {

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        Button button = (Button)findViewById(R.id.auth);
        final TextView textView1 = (TextView)findViewById(R.id.Access);


        button.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                try {
                    URL url = new URL("the url/oauth/token");
                    HttpURLConnection connection = (HttpURLConnection)url.openConnection();
                    connection.setRequestMethod("POST");
                    connection.setDoInput(true);
                    connection.setDoOutput(true);
                    connection.setRequestProperty("Content-type", "application/json");
                    connection.setRequestProperty("Accept", "application/json");
                    connection.setRequestProperty("grant_type", "password");
                    connection.setRequestProperty("username", "email address");
                    connection.setRequestProperty("password", "the password");
                    connection.setRequestProperty("client_id", "7777777");
                    connection.setRequestProperty("client_secret", "RKdZr2tgqS7pdCCR89rcywPJqpFguaZZ9JvbKj6LMWrvuSqK8jBLMq9gqkCQcwet");
                    connection.connect();
                    String response = connection.getResponseMessage();
                    textView1.setText(response);
                } catch (MalformedURLException e) {
                    e.printStackTrace();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        });
    }
}

Try to use AsyncTask in your code.

Here is my example:

public class ThemTask extends AsyncTask<TraSua,Void,Boolean> {
    Activity context;

    public ThemTask(Activity context){
        this.context=context;
    }
    @Override
    protected void onPreExecute() {
        super.onPreExecute();
    }

    @Override
    protected void onPostExecute(Boolean aBoolean) {
        super.onPostExecute(aBoolean);
        String s="Thêm thất bại";
        if(aBoolean==true){
            s="Thêm thành công";
        }
        Toast.makeText(context,s,Toast.LENGTH_LONG).show();
    }

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

    @Override
    protected Boolean doInBackground(TraSua... params) {

        try{
            TraSua ts=params[0];
            String param="?ban=" + ts.getBan() +
                    "&thucUong=" + ts.getThucUong() +
                    "&doAn=" + ts.getDoAn() +
                    "&them=" + ts.getThem();

            URL url=new URL("http://192.168.0.103/milktea/api/trasua"+param);
            HttpURLConnection connection= (HttpURLConnection) url.openConnection();
            connection.setRequestMethod("POST");
            connection.setRequestProperty("content-type","application/json; charset=utf-8");
            InputStreamReader streamReader=new InputStreamReader(connection.getInputStream(),"UTF-8");
            BufferedReader bufferedReader=new BufferedReader(streamReader);
            StringBuilder builder=new StringBuilder();
            String line=bufferedReader.readLine();
            while(line!=null){
                builder.append(line);
                line=bufferedReader.readLine();
            }
            String result=builder.toString();
            return result.contains("true");
        }catch(Exception e){
            Log.e("Loi_goi",e.toString());
        }
        return false;
    }
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM