Android请求web的方式

1:通过Java.net方式

a)直接通过URL传入参数的Get方式

HttpURLConnection con = (HttpURLConnection)url.openConnection();
InputStreamReader in = new InputStreamReader(con.getInputStream());
BufferedReader buffer = new BufferedReader(in);
				
while((inputLine=buffer.readLine())!=null){
	System.out.println(inputLine);
	strResult += inputLine + "\n";
}
				
in.close();
con.disconnect();

b)Post方式

con.setDoInput(true);
con.setDoOutput(true);

con.setRequestMethod("POST");
con.setUseCaches(false);
con.setInstanceFollowRedirects(false);
con.setRequestProperty("Content-Type","application/x-www-form-urlencoded");

con.connect();

DataOutputStream out = new DataOutputStream(con.getOutputStream());

String content = "par=" + URLEncoder.encode("1asdf");
out.writeBytes(content);

out.flush();
out.close();

InputStreamReader in = new InputStreamReader(con.getInputStream());
BufferedReader buffer = new BufferedReader(in);

while((inputLine=buffer.readLine())!=null){
	System.out.println(inputLine);
	strResult += inputLine + "\n";
}
buffer.close();
in.close();
con.disconnect();



 2:Apache

 

String httpUrl = "http://192.168.1.110:8080/httpget.jsp";
		//HttpPost连接对象
		HttpPost httpRequest = new HttpPost(httpUrl);
		//使用NameValuePair来保存要传递的Post参数
		List<NameValuePair> params = new ArrayList<NameValuePair>();
		//添加要传递的参数
		params.add(new BasicNameValuePair("par", "HttpClient_android_Post"));
		try
		{
			//设置字符集
			HttpEntity httpentity = new UrlEncodedFormEntity(params, "gb2312");
			//请求httpRequest
			httpRequest.setEntity(httpentity);
			//取得默认的HttpClient
			HttpClient httpclient = new DefaultHttpClient();
			//取得HttpResponse
			HttpResponse httpResponse = httpclient.execute(httpRequest);
			//HttpStatus.SC_OK表示连接成功
			if (httpResponse.getStatusLine().getStatusCode() == HttpStatus.SC_OK)
			{
				//取得返回的字符串
				String strResult = EntityUtils.toString(httpResponse.getEntity());
				mTextView.setText(strResult);
			}
			else
			{
				mTextView.setText("请求错误!");
			}
		}
		String httpUrl = "http://192.168.1.110:8080/httpget.jsp?par=HttpClient_android_Get";
		//HttpGet连接对象
		HttpGet httpRequest = new HttpGet(httpUrl);
		try
		{
			//取得HttpClient对象
			HttpClient httpclient = new DefaultHttpClient();
			//请求HttpClient,取得HttpResponse
			HttpResponse httpResponse = httpclient.execute(httpRequest);
			//请求成功
			if (httpResponse.getStatusLine().getStatusCode() == HttpStatus.SC_OK)
			{
				//取得返回的字符串
				String strResult = EntityUtils.toString(httpResponse.getEntity());
				mTextView.setText(strResult);
			}
			else
			{
				mTextView.setText("请求错误!");
			}
		}



 

3:通过Android.ent方式

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值