HTTP请求远端String和byte[]数据

package lizhen.http;

import java.io.IOException;

import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.HttpStatus;
import org.apache.http.client.ClientProtocolException;
import org.apache.http.client.HttpClient;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.util.EntityUtils;

public class HTTPRequest {
	
	private String errorMessage; //錯誤信息
	
	/**
	 * HTTP請求字符串資源
	 * @param url URL地址
	 * @return 字符串資源
	 * */
	public String httpRequestString(String url) {
		String result = null;
		try {
			HttpEntity httpEntity = httpRequest(url);
			if(httpEntity != null) {
				result = EntityUtils.toString(httpEntity, "urf-8"); //使用UTF-8編碼
			}
		} catch (IOException e) {
			errorMessage = e.getMessage();
		}
		return result;
	}
	
	/**
	 * HTTP請求字節數組資源
	 * @param url URL地址
	 * @return 字節數組資源
	 * */
	public byte[] httpRequestByteArray(String url) {
		byte[] result = null;
		try {
			HttpEntity httpEntity = httpRequest(url);
			if(httpEntity != null) {
				result = EntityUtils.toByteArray(httpEntity);
			}
		} catch (IOException e) {
			errorMessage = e.getMessage();
		}
		return result;
	}
	
	/**
	 * 使用HTTP GET方式請求
	 * @param url URL地址
	 * @return HttpEntiry對象
	 * */
	private HttpEntity httpRequest(String url) {
		HttpEntity result = null;
		try {
			HttpGet httpGet = new HttpGet(url);
			HttpClient httpClient = new DefaultHttpClient();
			HttpResponse httpResponse;
			httpResponse = httpClient.execute(httpGet);
			int httpStatusCode = httpResponse.getStatusLine().getStatusCode();
			/*
			 * 判斷HTTP狀態碼是否為200
			 * */
			if(httpStatusCode == HttpStatus.SC_OK) {
				result = httpResponse.getEntity();
			} else {
				errorMessage = "HTTP: "+httpStatusCode;
			}
		} catch (ClientProtocolException e) {
			errorMessage = e.getMessage();
		} catch (IOException e) {
			errorMessage = e.getMessage();
		}
		return result;
	}
	
	/**
	 * 返回錯誤消息
	 * @return 錯誤信息
	 * */
	public String getErrorMessage() {
		return this.errorMessage;
	}

}

示例代码使用HTTP Get方式请求远端资源。

httpRequestString方法适用于请求XML/JSON等文本资源。

httpRequestByteArray方法适用于请求图片/音乐等二进制资源。

当返回值为null时,调用getErrorMessage方法返回错误信息。


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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值