将DefaultHttpClient转换为HttpUrlConnection

时间:2015-10-07 13:52:28

标签: android http connection

大家好,所以我很难改变我为httpurlConnection创建的这些课程。我已经破坏了网络,我对httpUrlConnection

一点也不熟悉

应用流程:

来到MainActivity => OnTokenAcuired => GetCokie =>验证 然后我有一个httpPostRequest

MainActivity:
package com.ap2.demo.comunication;

import android.accounts.Account;
import android.accounts.AccountManager;
import android.app.Activity;
import android.content.Intent;
import android.support.v7.app.ActionBarActivity;
import android.os.Bundle;
import android.view.View;
import android.widget.ArrayAdapter;
import android.widget.Button;
import android.widget.ImageView;
import android.widget.Spinner;

import com.ap2.demo.R;
import com.ap2.demo.general.SplashActivity;

import org.apache.http.impl.client.DefaultHttpClient;

import java.util.ArrayList;

public class MainActivity extends Activity {
    AccountManager accountManager;
    private Account[] accounts;
    Spinner spinner;
    public static DefaultHttpClient httpClient  = new DefaultHttpClient();
    Account account;
    public static String email                  = "";
    ImageView img;
    public static boolean enteredOnce           = false;
    public static String uniqueIDPhone          = "";

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);

        accountManager = AccountManager.get(getApplicationContext());

        // assembling all gmail accounts
        accounts = accountManager.getAccountsByType("com.google");

        // add all gmail accounts :
        ArrayList<String> accountList = new ArrayList<String>();
        for (Account account : accounts) {
            accountList.add(account.name);
        }

        // setting spinner to be viewed
        spinner = (Spinner) findViewById(R.id.account);
        ArrayAdapter<String> dataAdapter = new ArrayAdapter<String>(this,
                android.R.layout.simple_spinner_item, accountList);
        dataAdapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
        spinner.setAdapter(dataAdapter);


        img = (ImageView) findViewById(R.id.splash_door);
        //Button startAuth = (Button) findViewById(R.id.startAuth);
        img.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                spinner = (Spinner) findViewById(R.id.account);
                account = accounts[spinner.getSelectedItemPosition()];
                email = account.name;
               // getIntent().putExtra("task", 1);
                accountManager.getAuthToken(account, "ah", null, false,
                        new OnTokenAcquired(httpClient, MainActivity.this), null);


                Intent intent = new Intent(MainActivity.this, SplashActivity.class);
                startActivity(intent);
            }
        });

    }

    protected void onActivityResult(int requestCode, int resultCode, Intent data)
    {
        if (resultCode == RESULT_OK) {
            accountManager.getAuthToken(account, "ah", null, false,
                    new OnTokenAcquired(httpClient, MainActivity.this), null);
        }
        else if(resultCode ==  RESULT_CANCELED){
            // user canceled
        }
    }

}


OnTokenAcquired:
package com.ap2.demo.comunication;

import android.accounts.AccountManager;
import android.accounts.AccountManagerCallback;
import android.accounts.AccountManagerFuture;
import android.app.Activity;
import android.content.Intent;
import android.os.Bundle;

import com.ap2.demo.enumPackage.Constants;

import org.apache.http.impl.client.DefaultHttpClient;

/**
 * Created by Daniel on 19-Jun-15.
 */
/*the result for the auth token request is returned to your application
via the Account Manager Callback you specified when making the request.
check the returned bundle if an Intent is stored against the AccountManager.KEY_INTENT key.
if there is an Intent then start the activity using that intent to ask for user permission
otherwise you can retrieve the auth token from the bundle.*/
public class OnTokenAcquired implements AccountManagerCallback<Bundle> {
    private static final int USER_PERMISSION = 989;

    private DefaultHttpClient httpclient;
    Activity activity;

    public OnTokenAcquired(DefaultHttpClient httpclient, Activity activity)
    {
        this.httpclient = httpclient;
        this.activity   = activity;
    }
    @Override
    public void run(AccountManagerFuture<Bundle> result) {
        Bundle bundle;

        try {
            bundle = (Bundle) result.getResult();
            if (bundle.containsKey(AccountManager.KEY_INTENT)) {
                Intent intent = bundle.getParcelable(AccountManager.KEY_INTENT);
                intent.setFlags(intent.getFlags() & ~Intent.FLAG_ACTIVITY_NEW_TASK);
                activity.startActivityForResult(intent, USER_PERMISSION);

            } else {
                setAuthToken(bundle);
            }
        }
        catch(Exception e){
            e.printStackTrace();
        }
    }

    //using the auth token and ask for a auth cookie
    protected void setAuthToken(Bundle bundle) {
        String authToken = bundle.getString(AccountManager.KEY_AUTHTOKEN);
        new GetCookie(httpclient, Constants.SERVER_REQUESTS.MY_APP_ID, activity.getBaseContext()).execute(authToken);
    }
}

package com.ap2.demo.comunication;

import android.content.Context;
import android.content.Intent;
import android.os.AsyncTask;

import com.ap2.demo.enumPackage.Constants;

import org.apache.http.HttpResponse;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.client.params.ClientPNames;
import org.apache.http.cookie.Cookie;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.params.HttpParams;

import java.io.ByteArrayOutputStream;

/**
 * Created by Daniel on 19-Jun-15.
 */
public class GetCookie extends AsyncTask<String, Void, Boolean> {
    String appId;
    HttpParams params;
    private HttpResponse response;
    Context context;
    private DefaultHttpClient httpclient;

    public GetCookie(DefaultHttpClient httpclient, String appId, Context context)
    {
        this.httpclient = httpclient;
        params = httpclient.getParams();
        this.appId = appId;
        this.context = context;
    }

    protected Boolean doInBackground(String... tokens) {

        try {

            // Don't follow redirects
            params.setBooleanParameter(ClientPNames.HANDLE_REDIRECTS, false);

            HttpGet httpGet = new HttpGet("http://" + appId
                    + ".appspot.com/_ah/login?continue=http://" + appId + ".appspot.com/&auth=" + tokens[0]);

            response = httpclient.execute(httpGet);
            ByteArrayOutputStream out = new ByteArrayOutputStream();
            response.getEntity().writeTo(out);
            out.close();

            if(response.getStatusLine().getStatusCode() != 302){
                // Response should be a redirect
                return false;
            }

            //check if we received the ACSID or the SACSID cookie, depends on http or https request
            for(Cookie cookie : httpclient.getCookieStore().getCookies()) {
                if(cookie.getName().equals("ACSID") || cookie.getName().equals("SACSID")){
                    return true;
                }
            }

        }  catch (Exception e) {
            e.printStackTrace();
            cancel(true);
        } finally {
            params.setBooleanParameter(ClientPNames.HANDLE_REDIRECTS, true);
        }
        return false;
    }

    protected void onPostExecute(Boolean result)
    {
        new Auth(httpclient, context).execute(Constants.SERVER_REQUESTS.LOGIN);
    }
}

package com.ap2.demo.comunication;

import android.content.Context;
import android.os.AsyncTask;
import android.telephony.TelephonyManager;
import android.widget.Toast;

import com.ap2.demo.R;
import com.ap2.demo.enumPackage.Constants;

import org.apache.http.HttpResponse;
import org.apache.http.HttpStatus;
import org.apache.http.StatusLine;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.impl.client.DefaultHttpClient;
import org.json.JSONException;
import org.json.JSONObject;

import java.io.ByteArrayOutputStream;

/**
 * Created by Daniel on 19-Jun-15.
 */
public class Auth extends AsyncTask<String, Void, Boolean> {

    private DefaultHttpClient httpclient;
    private HttpResponse response;
    private String content =  null;
    Context context;

    public Auth(DefaultHttpClient httpclient, Context context)
    {
        this.httpclient = httpclient;
        this.context = context;
    }

    protected Boolean doInBackground(String... urls) {

        try {

            HttpGet httpGet = new HttpGet(urls[0]);
            response = httpclient.execute(httpGet);
            StatusLine statusLine = response.getStatusLine();

            if(statusLine.getStatusCode() == HttpStatus.SC_OK){
                ByteArrayOutputStream out = new ByteArrayOutputStream();
                response.getEntity().writeTo(out);
                out.close();
                content = out.toString();
                return true;
            }
        } catch (Exception e) {
            e.printStackTrace();
            cancel(true);
        }
        return false;
    }

    //display the response from the request above
    protected void onPostExecute(Boolean result) {
        if (content != null) {
            try {
                System.out.print(result);
                JSONObject obj       = new JSONObject(content);
                String status = obj.getString(Constants.LOGIN_SERVICE.STATUS);
                if (status.equals(Constants.LOGIN_SERVICE.LOGIN_STATUS_OF_USER)) {
                    Toast.makeText(context, R.string.user_already_logged_in_status,
                            Toast.LENGTH_LONG).show();
                } else {
                    Toast.makeText(context, R.string.welcome_message,
                            Toast.LENGTH_LONG).show();
                }
            } catch (JSONException e) {
                Toast.makeText(context, R.string.failed_to_login + content,
                        Toast.LENGTH_LONG).show();
            }
        } else {
            Toast.makeText(context, R.string.could_not_loged_to_server,
                    Toast.LENGTH_LONG).show();
        }




    }
}

现在注意我使用相同的httpclient因为auth和cockie:

package com.ap2.demo.channels;

import android.app.Activity;
import android.os.AsyncTask;

import com.ap2.demo.comunication.MainActivity;
import com.ap2.demo.enumPackage.Constants;
import com.ap2.demo.main_activity.MapWithMarkers;

import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.NameValuePair;
import org.apache.http.client.ClientProtocolException;
import org.apache.http.client.entity.UrlEncodedFormEntity;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.message.BasicNameValuePair;

import java.io.IOException;
import java.io.InputStream;
import java.util.ArrayList;
import java.util.List;

/**
 * Created by Daniel on 30-Jun-15.
 */
public class ServerRequestAddChannel extends AsyncTask<String, String, String> {
    Activity activity;
    String name;
    public ServerRequestAddChannel(Activity activity, String name) {
        this.activity = activity;
        this.name = name;
    }
    @Override
    protected String doInBackground(String... params) {
        HttpPost httppost = new HttpPost(params[0]);

        try {
            // i have name and path only left id
            int idCounter = MapWithMarkers.id_counter++;
            // Add your data
            List<NameValuePair> nameValuePairs = new ArrayList<NameValuePair>(2);
            String name_of_channel = name;


            if (name.equals(Constants.REVIEWS_CHANNEL.NAME)) {
                // add special id to reviews channel
                nameValuePairs.add(new BasicNameValuePair(Constants.REVIEWS_CHANNEL.ID, Constants.REVIEWS_CHANNEL.ID));
            } else {
                name_of_channel = name + Integer.toString(idCounter);
                // taking off all free space for unique id
                name_of_channel = name_of_channel.replaceAll(" ","");
                nameValuePairs.add(new BasicNameValuePair(Constants.CHANNEL_REQUESTS.CHANNEL_TAG_ID, name_of_channel));
            }

            nameValuePairs.add(new BasicNameValuePair(Constants.CHANNEL_REQUESTS.CHANNEL_TAG_NAME, name));
            nameValuePairs.add(new BasicNameValuePair(Constants.CHANNEL_REQUESTS.CHANNEL_TAG_ICON, ""));

            // adding the channel to my new list
            if (!name_of_channel.equals(Constants.REVIEWS_CHANNEL.NAME)) {
                MapWithMarkers.channels_map.put(name_of_channel, new ChannelItem(name_of_channel, "", name));
                MapWithMarkers.my_subscriptions.add(name_of_channel);
            }


            httppost.setEntity(new UrlEncodedFormEntity(nameValuePairs));
            // Execute HTTP Post Request
            HttpResponse response = MainActivity.httpClient.execute(httppost);
            HttpEntity entity = response.getEntity();
            String text = getASCIIContentFromEntity(entity);
            return response.getStatusLine().getReasonPhrase().toString();

        } catch (ClientProtocolException e) {
            // TODO Auto-generated catch block
        } catch (IOException e) {
            // TODO Auto-generated catch block
        }
        return null;
    }
    protected void onPostExecute(String result) {
        ((AddChannelActivity) activity).moveToNextIntent();
    }
    protected String getASCIIContentFromEntity(HttpEntity entity)
            throws IllegalStateException, IOException {
        InputStream in = entity.getContent();
        StringBuffer out = new StringBuffer();
        int n = 1;
        while (n > 0) {
            byte[] b = new byte[4096];
            n = in.read(b);
            if (n > 0)
                out.append(new String(b, 0, n));
        }
        return out.toString();
    }
}

请帮助..

0 个答案:

没有答案