2016-01-21 64 views
1

我正在構建一個需要將用戶登錄到我們的服務器並且連接需要安全(HTTP)的android應用程序。我的問題是,我應該爲此使用OKHTTP庫嗎?OKHTTP是安全的嗎?

我使用圖書館登錄用戶如下:

public class MainActivity extends AppCompatActivity { 
public static final MediaType JSON 
     = MediaType.parse("application/json; charset=utf-8"); 
private static final String TAG = MainActivity.class.getSimpleName(); 
private JSONObject responseJson; 
@Override 
protected void onCreate(Bundle savedInstanceState) { 
    super.onCreate(savedInstanceState); 
    setContentView(R.layout.activity_main); 
    Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar); 
    setSupportActionBar(toolbar); 



    final JSONObject myJson = new JSONObject(); 
    try { 
     myJson.put("udid","c376e418-da42-39fb-0000-d821f1fd2804"); 
     myJson.put("email","email 
     myJson.put("password","password"); 
    } catch (JSONException e) { 
     e.printStackTrace(); 
    } 

     Thread thread = new Thread(new Runnable(){ 
      @Override 
      public void run() { 
       try { 
        //Your code goes here 
        String response = post("https://ADDRESS/v1/auth", myJson.toString()); 
        responseJson = new JSONObject(response); 
        String message = responseJson.getString("message"); 
        String token = responseJson.getString("token"); 
        Log.d(TAG,"Response message: " + message); 
        Log.d(TAG,"Response token: " + token); 
        Log.d("MainActivity",response); 
       } catch (Exception e) { 
        e.printStackTrace(); 
       } 
      } 
     }); 

     thread.start(); 

} 

String post(String url, String json) throws IOException { 
    OkHttpClient client = new OkHttpClient(); 
    RequestBody body = RequestBody.create(JSON, json); 
    Request request = new Request.Builder() 
      .url(url) 
      .post(body) 
      .build(); 
    Response response = client.newCall(request).execute(); 
    return response.body().string(); 
} 
} 
+1

如果您想進一步將其鎖定,請查看證書鎖定。這很危險,因爲您可以鎖定自己,它可以保護您免受本地設備上的一些安全問題。 –

回答

2

我應該使用OKHTTP庫用於這一目的?

OkHttp支持https URL,就像大多數Android客戶端HTTP客戶端庫一樣。

+0

謝謝你的回答。然而,我仍然不明白我使用它的方式是否安全(a.k.a.使用HTTPs發佈請求) –

+1

當然是這樣。 – Rohit5k2

+0

@ Rohit5k2謝謝你的回答!我希望能夠聽到,因爲我很喜歡使用這個庫是多麼簡單,並且不想經歷自己實現HttpsURLConnection的麻煩:p –