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. android9.0 系统默认时间修改
  2. android客户端程序访问服务器端webservice,几篇不错的文章!
  3. Android(安卓)双屏异显
  4. Android(安卓)办公自动化(Office Automation)
  5. Android之系统自带的文字外观设置及实际显示效果图 android:text
  6. Android中EditText属性
  7. Android(安卓)SearchView详细使用
  8. Android(安卓)各种音量的获取和设置
  9. View类xml属性、方法

随机推荐

  1. C#中操作Oracle时的SQL语句参数的用法
  2. 装了sql server 2005附加数据库成功,程序
  3. 如何将“u00e9”转换为一个utf8字符,在mys
  4. MYSQL从同一个表中选择标记关联的id
  5. 【整理】更改MSSQL默认字符集
  6. MySQL(三)——数据行 操作
  7. 求sql【复制同一表记录,但有两个字段需要
  8. [Python] - No.1 使用python3连接Mysql
  9. 从另一个表中的列更新列值
  10. 减去两个SELECT语句以产生单个结果?