【Android】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方法返回错误信息。
相关推荐
Kafka 2020-09-18
Wepe0 2020-10-30
杜倩 2020-10-29
windle 2020-10-29
minerd 2020-10-28
mengzuchao 2020-10-22
Junzizhiai 2020-10-10
bxqybxqy 2020-09-30
风之沙城 2020-09-24
kingszelda 2020-09-22
大唐帝国前营 2020-08-18
yixu0 2020-08-17
TangCuYu 2020-08-15
xiaoboliu00 2020-08-15
songshijiazuaa 2020-08-15
xclxcl 2020-08-03
zmzmmf 2020-08-03
newfarhui 2020-08-03
likesyour 2020-08-01