Переход с HTTP на HTTPS для всех подключений на веб-сервере - PullRequest
0 голосов
/ 15 апреля 2019

Я выполняю важное задание, и нас просят использовать HTTPS вместо HTTP для всех соединений с веб-сервером. У меня уже есть код с HTTP, но я не знаю, как изменить его на HTTPS. Этот код представляет методы, используемые для подключения к веб-серверу из приложения, созданного в Android Studio, и, как вы видите, мы расширили IntentService в классе.

public class ServerLibrary extends IntentService {

private static HttpTransportSE androidHttpTransport;
private static List<HeaderProperty> headerList_basicAuth;
private static final String WS_NAMESPACE = "http://sdm_webrepo/";
private static final String WS_METHOD_LIST = "ListCredentials";
private static final String WS_METHOD_IMPORT = "ImportRecord";
private static final String WS_METHOD_EXPORT = "ExportRecord";

//options for using HTTP + Basic Auth
private static final boolean USE_HTTPS = false;
private static final boolean USE_BASIC_AUTH = false;
private static final String BASIC_AUTH_USERNAME = "sdm";
private static final String BASIC_AUTH_PASSWORD = "repo4droid";
private static final String ANDROID_LOCALHOST = "10.0.2.2";

public static final String READ_FROM_SERVER = "read";
public static final String FETCH_FROM_SERVER = "fetch";
public static final String WRITE_TO_SERVER = "write";

public static final String READ_RECORDS = "list";
public static final String FETCH_RECORD = "record";
public static final String FETCH_ID = "id";
public static final String RECEIVER_TAG = "tagyoureit";
public static final String WRITE_RECORD_TAG = "record";

public ServerLibrary(){
    this("This should never happen but it needs a default constructor to be a valid service");
}

public ServerLibrary(String name) {
    super(name);
}

@Override
protected void onHandleIntent(Intent intent) {
    androidHttpTransport = new HttpTransportSE("http://"+ ANDROID_LOCALHOST +"/SDM/WebRepo?wsdl");
    headerList_basicAuth = new ArrayList<HeaderProperty>();
    String strUserPass = BASIC_AUTH_USERNAME + ":" + BASIC_AUTH_PASSWORD;
    headerList_basicAuth.add(new HeaderProperty("Authorization", "Basic " + org.kobjects.base64.Base64.encode(strUserPass.getBytes())));
    String action = intent.getAction();
    ResultReceiver rec = intent.getParcelableExtra(RECEIVER_TAG);
    switch(action){
        case READ_FROM_SERVER:
            try {
                List<Record> list = readFromServer();
                Bundle b=new Bundle();
                b.putParcelableArrayList(READ_RECORDS, new ArrayList<Record>(list));
                rec.send(0, b);
            } catch (Exception e) {
                e.printStackTrace();
            }
            break;
        case FETCH_FROM_SERVER:
            try {
                Record r = fetchRecordFromServerGivenID(intent.getExtras().getString(FETCH_ID));
                System.out.println("RECORD" + r + r.getId() + r.getUsername());
                Bundle b=new Bundle();
                b.putParcelable(FETCH_RECORD, r);
                rec.send(0, b);
            } catch (Exception e){
                e.printStackTrace();
            }
            break;
        case WRITE_TO_SERVER:
            try {
                writeToServer((Record) intent.getParcelableExtra(WRITE_RECORD_TAG));
            } catch (IOException e) {
                e.printStackTrace();
                rec.send(-1, null);
            } catch (XmlPullParserException e) {
                e.printStackTrace();
                rec.send(-1, null);
            }
            // only care about the status, no data to send
            rec.send(0, null);
            break;
    }
}

/*
  Read list of all record identifiers stored on the repository
 */
public List<Record> readFromServer() throws IOException, XmlPullParserException {
    List<Record> records = new ArrayList<Record>();
    SoapObject request = new SoapObject(WS_NAMESPACE, WS_METHOD_LIST);
    SoapSerializationEnvelope envelope = new SoapSerializationEnvelope(SoapEnvelope.VER11);
    envelope.setOutputSoapObject(request);
    androidHttpTransport.call("\"" + WS_NAMESPACE + WS_METHOD_LIST + "\"", envelope, headerList_basicAuth);
    Vector<SoapPrimitive> listIds = new Vector<SoapPrimitive>();
    if(envelope.getResponse() instanceof Vector) // 2+ elements
        listIds.addAll((Vector<SoapPrimitive>) envelope.getResponse());
    else if(envelope.getResponse() instanceof SoapPrimitive) // 1 element
        listIds.add((SoapPrimitive)envelope.getResponse());
    System.out.println("List of records stored on the repo: ");
    for(int i = 0; i < listIds.size(); i++)
    {
        System.out.println("- " + listIds.get(i).toString());
        records.add(new Record(listIds.get(i).toString(), null, null));
    }
    System.out.println();

    return records;
}

public Record fetchRecordFromServerGivenID(String id) throws IOException, XmlPullParserException {
    // Import existing record

    SoapObject request = new SoapObject(WS_NAMESPACE, WS_METHOD_LIST);
    SoapSerializationEnvelope envelope = new SoapSerializationEnvelope(SoapEnvelope.VER11);
    envelope.setOutputSoapObject(request);

    request = new SoapObject(WS_NAMESPACE, WS_METHOD_IMPORT);
    PropertyInfo propId = new PropertyInfo();
    propId.name = "arg0"; propId.setValue(id); propId.type = PropertyInfo.STRING_CLASS;
    request.addProperty(propId);
    envelope = new SoapSerializationEnvelope(SoapEnvelope.VER11);
    envelope.setOutputSoapObject(request);
    androidHttpTransport.call("\"" + WS_NAMESPACE + WS_METHOD_IMPORT + "\"", envelope, headerList_basicAuth);

    Vector<SoapPrimitive> importedRecord = (Vector<SoapPrimitive>)envelope.getResponse();
    if(importedRecord.size() == 3)
    {
        System.out.println("Record imported successfully: ");
        System.out.println("ID: " + importedRecord.get(0));
        System.out.println("Username: " + importedRecord.get(1));
        System.out.println("Password: " + importedRecord.get(2));
        return new Record(importedRecord.get(0).toString(), importedRecord.get(1).toString(), importedRecord.get(2).toString());
    }
    else
        System.out.println("Import error - " + importedRecord.get(0));
    return null;
}

/*
    Writes a record to the server
 */
public void writeToServer(Record r) throws IOException, XmlPullParserException {
    SoapObject request = new SoapObject(WS_NAMESPACE, WS_METHOD_EXPORT);
    PropertyInfo propId = new PropertyInfo();
    propId.name = "arg0"; propId.setValue(r.getId()); propId.type = PropertyInfo.STRING_CLASS;
    request.addProperty(propId);
    PropertyInfo propUser = new PropertyInfo();
    propUser.name = "arg1"; propUser.setValue(r.getUsername()); propUser.type = PropertyInfo.STRING_CLASS;
    request.addProperty(propUser);
    PropertyInfo propPass = new PropertyInfo();
    propPass.name = "arg2"; propPass.setValue(r.getPassword()); propPass.type = PropertyInfo.STRING_CLASS;
    request.addProperty(propPass);
    SoapSerializationEnvelope envelope = new SoapSerializationEnvelope(SoapEnvelope.VER11);
    envelope.setOutputSoapObject(request);
    androidHttpTransport.call("\"" + WS_NAMESPACE + WS_METHOD_EXPORT + "\"", envelope, headerList_basicAuth);
    System.out.println("Export result: " + envelope.getResponse().toString());
    System.out.println();
}


}
...