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请求安全认证
原文地址:http://blog.csdn.net/chenaini119/article/details/45557575