android 请求http数据格式化,Android HttpClient GET,POST 请求

importandroid.graphics.Bitmap;

importandroid.graphics.BitmapFactory;

importjava.io.File;

importjava.io.IOException;

importjava.io.InputStream;

importjava.net.HttpURLConnection;

importjava.net.URL;

importjava.security.KeyManagementException;

importjava.security.KeyStoreException;

importjava.security.NoSuchAlgorithmException;

importjava.security.cert.CertificateException;

importjava.util.ArrayList;

importjava.util.Date;

importjava.util.List;

importjava.util.Map;

importjavax.net.ssl.SSLContext;

importcz.msebera.android.httpclient.HttpEntity;

importcz.msebera.android.httpclient.HttpStatus;

importcz.msebera.android.httpclient.NameValuePair;

importcz.msebera.android.httpclient.client.entity.UrlEncodedFormEntity;

importcz.msebera.android.httpclient.client.methods.CloseableHttpResponse;

importcz.msebera.android.httpclient.client.methods.HttpGet;

importcz.msebera.android.httpclient.client.methods.HttpPost;

importcz.msebera.android.httpclient.conn.ssl.SSLConnectionSocketFactory;

importcz.msebera.android.httpclient.conn.ssl.TrustSelfSignedStrategy;

importcz.msebera.android.httpclient.impl.client.CloseableHttpClient;

importcz.msebera.android.httpclient.impl.client.HttpClients;

importcz.msebera.android.httpclient.message.BasicNameValuePair;

importcz.msebera.android.httpclient.ssl.SSLContexts;

importcz.msebera.android.httpclient.util.EntityUtils;

importcz.msebera.android.httpclient.util.TextUtils;

/*** the classes be used to request server url get response data*/public classRequestHttpClientUtil{

privateRequestHttpClientUtil(){}

/****@paramurlrequest url address*@paramparametersrequest parameters*@paramisAddArgsis or not ,add args to request address*@returnresponse data*/public staticStringdoHttpGet(Stringurl,

Map parameters,

booleanisAddArgs){

StringBuilderbuilder= newStringBuilder();

builder.append(url);

//先判断url后面是否有参数if(!url.contains("?")){

builder.append("?date="+String.valueOf(newDate().getTime()));

}

if(isAddArgs){

for(Map.Entry entry: parameters.entrySet()) {

builder.append("&");

builder.append(entry.getKey()+"="+(String)entry.getValue());

}

}

// LogUtils.i("请求为:"+builder.toString());CloseableHttpClienthttpclient= HttpClients.createDefault();

CloseableHttpResponseresponse= null;

try{

HttpGethttpget= newHttpGet(builder.toString());

response= httpclient.execute(httpget);

// LogUtils.i(response.getStatusLine()+"");HttpEntityresEntity= response.getEntity();

if(resEntity!= null) {

// LogUtils.i("Response content length: " + resEntity.getContentLength());returnEntityUtils.toString(resEntity);

}

return"false";

}catch(Exceptionexp){

LogUtils.e("get request error",exp);

}finally{

try{

if(httpclient!=null)

httpclient.close();

if(response!=null)

response.close();

} catch(IOExceptione) {

e.printStackTrace();

}

}

return"false";

}

/*** http post请求 分散参数提交(非同一个对象的参数)*@paramurl请求地址,*@paramparameters请求参数*@return响应数据字符串*/public staticStringdoHttpPost(Stringurl,

Map parameters){

CloseableHttpClienthttpclient= HttpClients.createDefault();

CloseableHttpResponseresponse= null;

try{

HttpPosthttppost= newHttpPost(url);

List params= newArrayList<>();

for(Map.Entry entry: parameters.entrySet()) {

params.add(newBasicNameValuePair(

entry.getKey(),

(String)entry.getValue()

));

}

HttpEntityreqEntity= newUrlEncodedFormEntity(params, "UTF-8");

httppost.setEntity(reqEntity);

// LogUtils.i("executing request " + httppost.getRequestLine());response= httpclient.execute(httppost);

// LogUtils.i(response.getStatusLine().getStatusCode()+"");if(response.getStatusLine().getStatusCode() == HttpStatus.SC_OK){

returnEntityUtils.toString(response.getEntity());

}

return"false";

} catch(IOExceptione) {

LogUtils.e("POST request error",e);

}finally{

try{

if(response!=null)

response.close();

if(httpclient!=null)

httpclient.close();

} catch(IOExceptione) {

e.printStackTrace();

}

}

return"false";

}

/***提交一个对象到服务器 并获得返回值*@paramurl请求地址*@paramt需要提交的实体对象(参数)*@paramclazz实体对象的类型*@paramClazz*@return返回结果*/public static StringdoHttpPostSubmitAObject(Stringurl,

Tt,

Class clazz){

CloseableHttpClienthttpclient= HttpClients.createDefault();

CloseableHttpResponseresponse= null;

try{

HttpPosthttppost= newHttpPost(url);

List params=

SubmitArgsUtils.getSubmitArgs(t,clazz);

HttpEntityreqEntity=

newUrlEncodedFormEntity(params, "UTF-8");

httppost.setEntity(reqEntity);

// LogUtils.i("executing request " + httppost.getRequestLine());response= httpclient.execute(httppost);

// LogUtils.i(response.getStatusLine().getStatusCode()+"");if(response.getStatusLine().getStatusCode() == HttpStatus.SC_OK){

returnEntityUtils.toString(response.getEntity());

}

return"false";

} catch(IOExceptione) {

LogUtils.e("do post submit a object error",e);

}finally{

try{

if(response!=null)

response.close();

if(httpclient!=null)

httpclient.close();

} catch(IOExceptione) {

e.printStackTrace();

}

}

return"false";

}

/***自定义证书的https请求*@paramkeyStore证书文件路径*@parampassword证书密码*@paramurl请求地址*@paramparameters请求参数*@paramisAddArgs是否将请求参数追加到路径上 如果为false GET*请求直接发请求到url如果为true会将参数追加到url后面提交*@return响应结果*/public staticStringdoCustomSSLHttpsGet(StringkeyStore,

Stringpassword,

Stringurl,

Map parameters,

booleanisAddArgs){

StringBuilderbulider= newStringBuilder();

bulider.append(url);

//先判断url后面是否有参数if(!url.contains("?")){

bulider.append("?");

}

bulider.append("temp="+String.valueOf(newDate().getTime()));

if(isAddArgs){

for(Map.Entry entry: parameters.entrySet()) {

bulider.append("&");

bulider.append(entry.getKey()+"="+(String)entry.getValue());

}

}

CloseableHttpClienthttpclient= getHttpClient(keyStore,password);

CloseableHttpResponseresponse= null;

try{

HttpGethttpget= newHttpGet(bulider.toString());

response= httpclient.execute(httpget);

HttpEntityresEntity= response.getEntity();

if(resEntity!= null) {

returnEntityUtils.toString(resEntity);

}

return"false";

}catch(Exceptionexp){

exp.printStackTrace();

}finally{

try{

if(response!=null){

response.close();

}

httpclient.close();

} catch(IOExceptione) {

e.printStackTrace();

}

}

return"false";

}

/***自定义证书的https post请求 非同一个对象的数据提交*@paramurl请求地址*@paramparameters请求参数*@return响应结果*/public staticStringdoCustomSSLHttpsPost(StringkeyStore,Stringpassword,

Stringurl,

Map parameters) {

CloseableHttpClienthttpclient= getHttpClient(keyStore,password);

CloseableHttpResponseresponse= null;

try{

HttpPosthttppost= newHttpPost(url);

List params= newArrayList<>();

for(Map.Entry entry: parameters.entrySet()) {

// System.out.println("Key = " + entry.getKey() + ", Value = " + entry.getValue());params.add(newBasicNameValuePair(entry.getKey(), (String)entry.getValue()));

}

HttpEntityreqEntity= newUrlEncodedFormEntity(params, "UTF-8");

httppost.setEntity(reqEntity);

// System.out.println("executing request " + httppost.getRequestLine());response= httpclient.execute(httppost);

// System.out.println(response.getStatusLine().getStatusCode());if(response.getStatusLine().getStatusCode() == HttpStatus.SC_OK){

returnEntityUtils.toString(response.getEntity());

}

return"false";

} catch(Exceptione) {

e.printStackTrace();

}finally{

try{

if(response!=null){

response.close();

}

httpclient.close();

} catch(IOExceptione) {

e.printStackTrace();

}

}

return"false";

}

/***获取自定义CloseableHttpClient用于自定义证书 的https的请求*@paramkeyStore证书文件路径*@parampassword证书密码*@returnCloseableHttpClient*/private staticCloseableHttpClientgetHttpClient(StringkeyStore,Stringpassword){

if(TextUtils.isEmpty(keyStore)){

returnHttpClients.createDefault();

}

if(TextUtils.isEmpty(password)){

returnHttpClients.createDefault();

}

// Trust own CA and all self-signed certsSSLContextsslcontext;

try{

sslcontext= SSLContexts.custom()

.loadTrustMaterial(newFile(keyStore), password.toCharArray(),

newTrustSelfSignedStrategy())

.build();

// Allow TLSv1 protocol onlySSLConnectionSocketFactorysslsf=

newSSLConnectionSocketFactory(

sslcontext,

newString[] { "TLSv1"},

null,

SSLConnectionSocketFactory.getDefaultHostnameVerifier());

returnHttpClients.custom()

.setSSLSocketFactory(sslsf)

.build();

} catch(KeyManagementException|

NoSuchAlgorithmException|

KeyStoreException|

CertificateException|

IOExceptione) {

throw newIllegalArgumentException("请确认.keyStore文件路径和密码是否匹配");

}

}

/***@paramurlrequest http address*@paramrequestMethodrequest method "POST" or "GET"*@paramisCachesis or not need caches*@returnBitmap image data*/public staticBitmaprequestHttpBitmap(Stringurl,

StringrequestMethod,

BooleanisCaches){

URLmyFileURL;

Bitmapbitmap=null;

try{

myFileURL= newURL(url);

//获得连接HttpURLConnectionconn=(HttpURLConnection)myFileURL.openConnection();

//设置超时时间为6000毫秒,conn.setConnectionTiem(0);表示没有时间限制conn.setConnectTimeout(10000);

conn.setRequestMethod(requestMethod);

//连接设置获得数据流conn.setDoInput(true);

//不使用缓存conn.setUseCaches(isCaches);

//这句可有可无,没有影响//conn.connect();//得到数据流InputStreamis= conn.getInputStream();

//解析得到图片bitmap= BitmapFactory.decodeStream(is);

//关闭数据流is.close();

}catch(Exceptione){

LogUtils.e("失败",e);

}

returnbitmap;

}

}

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值