android http连接服务器

判断网络连接情况
public static boolean isConnected(Context context) {
// <span class="comment" style="margin: 0px; padding: 0px; border: none; color: rgb(0, 130, 0); font-family: Consolas, 'Courier New', Courier, mono, serif; line-height: 18px;">ConnectivityManager主要管理和网络连接相关的操作</span><span style="font-family: Consolas, 'Courier New', Courier, mono, serif; line-height: 18px;"> </span>
ConnectivityManager conManager = (ConnectivityManager) context
.getSystemService(Context.CONNECTIVITY_SERVICE);

// 网络信息 <span class="comment" style="margin: 0px; padding: 0px; border: none; color: rgb(0, 130, 0); font-family: Consolas, 'Courier New', Courier, mono, serif; line-height: 18px; background-color: rgb(248, 248, 248);">NetworkInfo类包含了对wifi和mobile两种网络模式连接的详细描述</span>
NetworkInfo networkInfo = conManager.getActiveNetworkInfo();

// 检查网络
if (networkInfo != null) {
return conManager.getActiveNetworkInfo().isConnected();
}

return false;
}
httppost通过post机制将提价的表单放在html header中用户在URL中看不到
post将数据放在List<<span style="font-family: Arial, Helvetica, sans-serif;">NameValuePair</span>>中
<pre name="code" class="java">/**
	 * HTTP Post 通信处理
	 * @param context 
	 * @param apiUrl 
	 * @param nameValuePair 
	 * @return String
	 * @throws Exception
	 */
	public static String httpPost(Context context, String apiUrl, List<NameValuePair> nameValuePair, String baseUserAgent) throws Exception {

		//HttpClient
		HttpClient httpClient = new DefaultHttpClient();

		HttpParams httpParameters = new BasicHttpParams();
		HttpConnectionParams.setConnectionTimeout(httpParameters, 10000);
		HttpConnectionParams.setSoTimeout(httpParameters, 10000);

		try {
			baseUserAgent = baseUserAgent + AppInfoUtil.getAppVersionName(context);
		} catch(Exception e) {
			return "";
		}
		baseUserAgent = baseUserAgent + " " + httpClient.getParams().getParameter("http.useragent");

		//(http.useragent)
		httpClient.getParams().setParameter("http.useragent", baseUserAgent);

		//HTTP Post
		HttpPost httppost = new HttpPost(apiUrl);
		int responseCode = 0;
		String result = "";

		httppost.setEntity(new UrlEncodedFormEntity(nameValuePair, HTTP.UTF_8));
		//HTTP post通信
		HttpResponse response = httpClient.execute(httppost);
		

		//返回值
		responseCode = response.getStatusLine().getStatusCode();
		if(responseCode == HttpStatus.SC_OK) {

			ByteArrayOutputStream byteArrayOutputStream = new ByteArrayOutputStream();
			response.getEntity().writeTo(byteArrayOutputStream);
			result = byteArrayOutputStream.toString();
		} else if(responseCode == HttpStatus.SC_NOT_FOUND) {

			//服务器连接失败
			throw new FileNotFoundException();
		} else if(responseCode == HttpStatus.SC_REQUEST_TIMEOUT) {

			//连接超时
			throw new Exception();
		}
		
		return result;
	}
get将表单拼接到url中,用户是可以看到的

 
get将数据拼到url后面 eg http://172.23.1.23//api01/?username=""&pwd=""
<pre name="code" class="java">/**
	 * HTTP GET通信
	 * @param url
	 * @return
	 * @throws Exception 
	 */
	public static String httpGet2(Context context, String url, String userAgent) throws Exception  {
		// offline
		// 网络连接确认
		if (NetworkUtil.isConnected(context) == false) {
			throw new Exception();
		}
//		HttpParams httpParameters = new BasicHttpParams();
//        HttpConnectionParams.setConnectionTimeout(httpParameters, 40000);
//        HttpConnectionParams.setSoTimeout(httpParameters, 40000);
//        HttpClient httpClient = new DefaultHttpClient(httpParameters);
		App app = (App)((Activity)context).getApplication();
		HttpClient httpClient = app.getHttpClient();
//
//		HttpParams params = httpClient.getParams();
//
//		HttpConnectionParams.setConnectionTimeout(params, 10000);
//		HttpConnectionParams.setSoTimeout(params, 10000);


		HttpGet request = new HttpGet(url);
		request.addHeader(Constant.USER_AGENT, userAgent);
		HttpResponse httpResponse = null;

		try {
			httpResponse = httpClient.execute(request);
			// 通信失败
			if (httpResponse == null) {
				throw new Exception();
			}
		}catch (Exception e) {
			TCILog.e("myTask", "HTTP error === " + e.getMessage());
			throw new Exception();
		}

		String response = null;
		if (httpResponse != null
				&& httpResponse.getStatusLine().getStatusCode() == HttpStatus.SC_OK) {
			HttpEntity httpEntity = httpResponse.getEntity();
			try {
				response = EntityUtils.toString(httpEntity);
			} catch (Exception e) {
				TCILog.e("myTask", "EntityUtils.toString error === " + e.getMessage());
				throw new Exception();
			} finally {
				try {
					httpEntity.consumeContent();
				} catch (IOException e) {
					TCILog.e("myTask", "httpEntity.consumeContent error === " + e.getMessage());
					throw new Exception();
				}
			}
		} else {
			HttpEntity httpEntity = httpResponse.getEntity();
			
			try {
				response = EntityUtils.toString(httpEntity);
			} catch (Exception e) {
				TCILog.e("myTask", "EntityUtils.toString === " + e.getMessage());
				throw new Exception();
			}
			throw new Exception();
		}
		return response;

	}


 


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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值