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请求

更多相关文章

  1. 解析ANDROID ps命令执行后各项参数的含义
  2. Android数字证书
  3. 布局中文件中【控件间距参数详解以及单位选择】
  4. Android LayoutInflater.inflate(R.layout.activity_test, conta
  5. android 音乐信息乱码处理
  6. Android 项目生成证书指纹(MD5、SHA1、SHA256)
  7. AndroidStudio用gradle编译中文乱码
  8. Android性能检测--traceview工具各个参数的意思
  9. Android Studio3.1.2 build.gradle classpath参数报错

随机推荐

  1. 韩顺平 javascript教学视频_学习笔记12_j
  2. setInterval在Chrome上不能正常工作
  3. ajaxComplete射击多次- woocommerce添加
  4. 在用户将'n'粘贴复制到文本字段后,如何更
  5. 咕噜、NPM和俯卧撑(包)的区别。json vs鲍
  6. contains和compareDocumentPosition 方法
  7. jquery ajax readystate 0 responsetext
  8. 显示或不显示。
  9. 使用JavaScript显示HTML文本框中剩余的字
  10. ArcGIS API For JavaScript 实现鼠标移入