Web服务

与外界通信的一种常用方法是HTTP,HTTP是推动WEB走向成功的一种协议。通过使用HTTP,可以从Web服务器下载网页、下载二进制数据等。

JSON(JavaScript Object Notation)是一种轻量级的数据交换格式,便于人们读写,同时也易于机器解析和生成。

主要使用的包有java.net, java.io, org.json

1、通过HTTP使用WEB服务

public void onClick(View v){
	switch (v.getId()) {
	case R.id.btn:
		new DownloadThread("http://qinuli.com/picture/hand_in_hand.jpg").start();
	}
}
/**
 * 下载图片字节流
 * @param urlString 图片网址
 * @return 图片字节流
 */
private InputStream getInputStream(String urlString){
	InputStream inputStream = null;
	int response = -1;
	try {
		URL url = new URL(urlString);
		HttpURLConnection httpURLConnection = (HttpURLConnection) url.openConnection();
		httpURLConnection.setAllowUserInteraction(false);
		httpURLConnection.setInstanceFollowRedirects(true);
		httpURLConnection.setRequestMethod("GET");
		httpURLConnection.connect();
		response = httpURLConnection.getResponseCode();
		if(response == HttpURLConnection.HTTP_OK){
			inputStream = httpURLConnection.getInputStream();
		}
	} catch (Exception e) {
		e.printStackTrace();
	}
	return inputStream;
}
Handler mHandler = new Handler();
private class DownloadThread extends Thread{
	String[] mURLs;
	public DownloadThread(String... urls){
		mURLs = urls;
	}
	@Override
	public void run() {
		super.run();
		//拿到图片字节流
		InputStream inputStream = getInputStream(mURLs[0]);
		File file = new File(Environment.getExternalStorageDirectory(), "hand_in_hand.jpg");
		try {
			//将字节流写到文件
			OutputStream outputStream = new FileOutputStream(file);
			byte[] bytes = new byte[1024];
			int length = -1;
			while((length=inputStream.read(bytes))!=-1){
				outputStream.write(bytes, 0, length);
			}
			inputStream.close();
			outputStream.close();
			//将创建完的SD卡图片文件设置到ImageView
			final Bitmap bitmap = BitmapFactory.decodeFile(file.getPath());
			mHandler.post(new Runnable() {
				@Override
				public void run() {
					ImageView imageView = (ImageView) findViewById(R.id.img);
					imageView.setImageBitmap(bitmap);
				}
			});
		} catch (FileNotFoundException e1) {
			e1.printStackTrace();
		} catch (IOException e) {
			e.printStackTrace();
		}
	}
}

2、JSON示例演示

public void onClick(View v){
	switch (v.getId()) {
	case R.id.btn:
		new DownloadThread("http://qinuli.com/web/json.html").start();
	}
}
private String readJSONFeed(String url){
	StringBuilder stringBuilder = new StringBuilder();
	HttpClient httpClient = new DefaultHttpClient();
	HttpGet httpGet = new HttpGet(url);
	try {
		//If network is unavailable, throw UnknownHostException.
		HttpResponse httpResponse = httpClient.execute(httpGet);
		StatusLine statusLine = httpResponse.getStatusLine();
		int statusCode = statusLine.getStatusCode();
		if(statusCode == 200){
			HttpEntity httpEntity = httpResponse.getEntity();
			InputStream inputStream = httpEntity.getContent();
			BufferedReader bufferedReader = new BufferedReader(new InputStreamReader(inputStream));
			String line;
			while((line=bufferedReader.readLine())!=null){
				stringBuilder.append(line);
			}
		}else{
			Log.e(TAG, "failed to download file");
		}
	} catch (ClientProtocolException e) {
		e.printStackTrace();
	} catch (IOException e) {
		e.printStackTrace();
	}
	return stringBuilder.toString();
}
private class DownloadThread extends Thread{
	String[] mURLs;
	public DownloadThread(String... urls){
		mURLs = urls;
	}
	@Override
	public void run() {
		super.run();
		Looper.prepare();
		for(int i=0;i<mURLs.length;i++){
			String result = readJSONFeed(mURLs[i]);
			if("".equals(result)){//no network or no data
				break;
			}
			try {
				JSONArray jsonArray = new JSONArray(result);
				StringBuilder stringBuilder = new StringBuilder();
				for(int j=0;j<jsonArray.length();j++){
					JSONObject jsonObject = jsonArray.getJSONObject(j);
					stringBuilder.append(jsonObject.get("id")).append("|")
					.append(jsonObject.get("name")).append("|")
					.append(jsonObject.get("sex")).append('\n');
				}
				Toast.makeText(SecondActivity.this, stringBuilder.deleteCharAt(stringBuilder.length()-1), Toast.LENGTH_SHORT).show();
			} catch (JSONException e) {
				e.printStackTrace();
			}
		}
		Looper.loop();
		Looper.myLooper().quit();
	}
}
权限:<uses-permission android:name="android.permission.INTERNET"/>

断网会报异常:


3、XML演示

private class MyThread extends Thread{
	@Override
	public void run() {
		super.run();
		try {
			URL url = new URL("http://qinuli.com/web/updateinfo.xml");
			HttpURLConnection httpURLConnection = (HttpURLConnection) url.openConnection();
			httpURLConnection.setConnectTimeout(5000);
			httpURLConnection.setRequestMethod("GET");
			InputStream inputStream = null;
			if(httpURLConnection.getResponseCode() == HttpURLConnection.HTTP_OK){
				inputStream = httpURLConnection.getInputStream();
			}else if(httpURLConnection.getResponseCode() == HttpURLConnection.HTTP_NOT_FOUND){
				//域名错误
			}
			StringBuilder stringBuilder = new StringBuilder();
			XmlPullParser xmlPullParser = Xml.newPullParser();
			xmlPullParser.setInput(inputStream, "UTF-8");
			int eventType = xmlPullParser.getEventType();
			while(eventType!=XmlPullParser.END_DOCUMENT){
				switch (eventType) {
				case XmlPullParser.START_TAG:
					if("updateInfo".equals(xmlPullParser.getName())){
						stringBuilder.append("updateinfo")
							.append('(');
					}else if("version".equals(xmlPullParser.getName())){
						stringBuilder.append(xmlPullParser.nextText())
							.append(',');
					}else if("url".equals(xmlPullParser.getName())){
						stringBuilder.append(xmlPullParser.nextText())
							.append(',');
					}else if("description".equals(xmlPullParser.getName())){
						stringBuilder.append(xmlPullParser.nextText())
							.append(',');
					}
				}
				eventType = xmlPullParser.next();
			}
			Log.i(TAG, stringBuilder.deleteCharAt(stringBuilder.length()-1).append(')').toString());
		} catch (MalformedURLException e) {
			e.printStackTrace();
		} catch (IOException e) {
			e.printStackTrace();
		} catch (XmlPullParserException e) {
			e.printStackTrace();
		}
	}
}

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值