android json實現網路請求 和普通的http請求 還有https請求安全認證

來源:互聯網
上載者:User

標籤:android   http https   

android 實現http請求很多種,和伺服器對接需要瞭解 

在 Android 下,Android SDK 已經為我們封裝好了整個與 JSON 有關的操作,使用非常方便

直接上代碼

/**
* 發送 http 請求

* @param url
*/
@SuppressLint("DefaultLocale")
public int httpResponseCodeJsonPost(String strUrl, String authorization,
String currentSessionId, String ClientId,
PostParameter[] postParams, String httpMethod)
throws SystemException {
int responseCode = -1;
try {
HttpPost request = new HttpPost(strUrl);
JSONObject param = new JSONObject();
for (int j = 0; j < postParams.length; j++) {
param.put(postParams[j].name, 
postParams[j].value);//設定參數
}
try {
StringEntity se = new StringEntity(param.toString(),"utf-8");//防止亂碼
request.setEntity(se);
} catch (UnsupportedEncodingException e1) {
// TODO Auto-generated catch block
e1.printStackTrace();
}
request.getParams().setParameter(CoreConnectionPNames.CONNECTION_TIMEOUT, 5000);
request.getParams().setParameter(CoreConnectionPNames.SO_TIMEOUT, 5000);//設定逾時
request.setHeader("X-FBox-Session", currentSessionId);
request.setHeader("Authorization", authorization);//設定各種頭
request.setHeader("X-FBox-ClientId", ClientId);
request.setHeader("Content-Type",
"application/json;charset=UTF-8");
// 發送請求
try {
HttpResponse httpResponse = new DefaultHttpClient()
.execute(request);

                               //String retSrc = EntityUtils.toString(httpResponse.getEntity());  //返回結果

responseCode = httpResponse.getStatusLine().getStatusCode();//返回狀態
} catch (ClientProtocolException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
} catch (JSONException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
return responseCode;
}

這裡基本包括了全部過程。和一些考慮亂碼問題。

下面一段是普通的http請求

/**
* 發送 http 請求

* @param url
*/
@SuppressLint("DefaultLocale")
public int httpResponseCode(String strUrl, String authorization,
String currentSessionId, String ClientId,
PostParameter[] postParams, String httpMethod)
throws SystemException {
int retriedCount;
int retry = 1;
Response res = null;
int responseCode = -1;
for (retriedCount = 0; retriedCount < retry; retriedCount++) {
try {
HttpURLConnection con = null;
OutputStream osw = null;
URL url = new URL(strUrl);
try {
con = (HttpURLConnection) url.openConnection();
con.setDoInput(true);
con.setRequestProperty("Authorization", authorization);

con.addRequestProperty("X-FBox-ClientId", ClientId);
setHeaders(strUrl, postParams, con, httpMethod);
if ("POST".equals(httpMethod) || "PUT".equals(httpMethod)) {// null
// 將當前HTTP請求方式設定為"POST"
con.setRequestMethod(httpMethod);
// 參數值為true時決定著當前連結可以進行資料提交工作
con.setRequestProperty("Content-Type",
"application/x-www-form-urlencoded");
con.setDoOutput(true);
String postParam = "";
if (postParams != null) {
postParam = encodeParameters(postParams);
}
byte[] bytes = postParam.getBytes("UTF-8");
// 設定檔案長度
con.setRequestProperty("Content-Length",
Integer.toString(bytes.length));
osw = con.getOutputStream();
osw.write(bytes);
osw.flush();
osw.close();
} else {
con.setRequestMethod(httpMethod);
}
con.setConnectTimeout(this.connectionTimeout);
con.setReadTimeout(this.readTimeout);
res = new Response(con);
responseCode = con.getResponseCode();
} finally {
try {
osw.close();
} catch (Exception ignore) {
}
}
} catch (IOException ioe) {
// connection timeout or read timeout
if (retriedCount == 1) {// retryCount
throw new SystemException(ioe.getMessage(), ioe,
responseCode);
}
}
}
return responseCode;
}

這是  application/x-www-form-urlencoded 類型的請求方式。

這裡只是普通的請求http

有時候我們遇到https請求那隻要加上下面的


if (url.getProtocol().toLowerCase().equals("https")) {
trustAllHosts();//信任所有
HttpsURLConnection https = (HttpsURLConnection) url
.openConnection();
https.setHostnameVerifier(DO_NOT_VERIFY);
con = https;
} else {
con = (HttpURLConnection) url.openConnection();
}


/**
* 信任所有主機-對於任何認證都不做檢查
*/
@SuppressLint("TrulyRandom")
private static void trustAllHosts() {
// Create a trust manager that does not validate certificate chains
// Android 採用X509的認證資訊機制
TrustManager[] trustAllCerts = new TrustManager[] { new X509TrustManager() {
public java.security.cert.X509Certificate[] getAcceptedIssuers() {
return new java.security.cert.X509Certificate[] {};
}


public void checkClientTrusted(X509Certificate[] chain,
String authType) throws CertificateException {
}


public void checkServerTrusted(X509Certificate[] chain,
String authType) throws CertificateException {
}
} };


// Install the all-trusting trust manager
try {
SSLContext sc = SSLContext.getInstance("TLS");
sc.init(null, trustAllCerts, new java.security.SecureRandom());
HttpsURLConnection
.setDefaultSSLSocketFactory(sc.getSocketFactory());
} catch (Exception e) {
e.printStackTrace();
}
}

這樣就可以訪問有認證的https請求

android json實現網路請求 和普通的http請求 還有https請求安全認證

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.