2016-01-21 132 views
0

我正在尋找一種方式如何在android中進行POST(登錄)https請求。如何確保代碼不信任自籤/無效證書。輸入請求需要在以下格式:如何在Android中創建POST HTTPs(帶有JSON)請求?

{ 
"udid": DEVICE_ID 
"email": "[email protected]", 
"password": "password" 
} 

我需要做AUTH調用該地址格式:

https://api.ADDRESS.com/v1/auth 

請注意,我想使用HTTPS請求,而不是HTTP。

+0

這不是重複,因爲我想使用HTTPS和不HTTP .. –

+0

好吧,但它應該是相同的,你的API將得到http https分別爲 –

+0

我不確定它是一樣的。我需要生成證書才能建立安全的HTTP連接,我不知道該怎麼做...... –

回答

0

我結束了使用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(); 
} 
}