Android HTTP请求处理

private static final int REQUEST_TIMEOUT = 20 * 1000;// 设置请求超时10秒钟


public static String encode(String URL) 
{
String result = URL;
if (CommonUtil.isNotEmpty(URL)) 
{
try 
{
result = URLEncoder.encode(URL, "UTF-8");

catch (UnsupportedEncodingException e) 
{
e.printStackTrace();
}
}
return result;
}


public static String getInfomations(String url) 
{
String value = null;
try 
{
if (CommonUtil.isNotEmpty(url)) 
{
url= url.replaceAll(" ", "%20");
/*
*  创建一个http客户端 
*/
HttpClient client = new DefaultHttpClient();

/*
* 设置超时处理
*/
getHttpClient(client);

/*
*  创建一个GET请求
*/
HttpGet httpGet = new HttpGet(url);


/*
*  向服务器发送请求并获取服务器返回的结果
*/
HttpResponse response = client.execute(httpGet);
HttpEntity entity = response.getEntity();

if (null != entity) 
{
/*
*  返回的结果可能放到InputStream,http
*/
InputStream inputStream = entity.getContent(); 

/*
*  解析流
*/
value = Parser.Reader(inputStream);
}
else
{
CommonUtil.log("server entity is null...");
}
}
}
catch (Exception e)
{
e.printStackTrace();
}
return value;
}


public static void getHttpClient(HttpClient client) {
HttpParams httpParams = client.getParams();
HttpConnectionParams.setConnectionTimeout(httpParams, REQUEST_TIMEOUT);
HttpConnectionParams.setSoTimeout(httpParams, SO_TIMEOUT);
// HttpClient client = new DefaultHttpClient(httpParams);
}


/**

* parser inputStream

* @param inputStream
* @return
*/
public static String Reader(InputStream inputStream) 
{
String sCurrentLine = null;
String sTotalString = null;
try 
{
BufferedReader bufferedReader = new BufferedReader(new InputStreamReader(inputStream));
StringBuffer stemp = new StringBuffer();
while ((sCurrentLine = bufferedReader.readLine()) != null) 
{
stemp.append(sCurrentLine);
}
sTotalString = stemp.toString();

catch (IOException e) 
{
e.printStackTrace();

finally 
{
if (null != inputStream) 
{
try
{
inputStream.close();

catch (IOException e) 
{
e.printStackTrace();
}
}
}
return sTotalString;
}

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值