利用Android自带的http包进行网络请求

目的是为了不依赖第三方的jar包进行网络请求(如:commons-httpclient.jar)

修改了一下,可以自定义请求的Header,增加了对POST表单数据的支持。

1. 建立一个连接配置类

class UserAgentConfig {
public String host;
public String scheme = "http";
public int port = 80;
public int timeoutConnection = 3000;
public int timeoutSocket = 20000;
public String username = "";
public String password = "";
}

2. 封装请求类

public class HttpRequest {

private String mUrl;
private UserAgentConfig mConfig = null;
private HashMap<String, String> mHeaders = null;
private HttpEntity mBody = null;
private int mStatus = -1;

public HttpRequest(String url) {
mUrl = url;
}

public void addHeader(String key, String value) {
if (mHeaders == null)
mHeaders = new HashMap<String, String>();

mHeaders.put(key, value);
}

public void clearHeader() {
mHeaders.clear();
mHeaders = null;
}

public void setConfig(UserAgentConfig config) {
mConfig = config;
}

public void setPostBody(List<BasicNameValuePair> body) {
try {
mBody = new UrlEncodedFormEntity(body, "utf-8");
} catch (UnsupportedEncodingException e) {
e.printStackTrace();
}
}

public void setPostBody(String body) {
try {
mBody = new StringEntity(body);
} catch (UnsupportedEncodingException e) {
e.printStackTrace();
}
}

public void execute() throws ClientProtocolException, IOException {
httprequest();
}

public int getStatusCode() {
return mStatus;
}

/**
* get "Stream" as response
*
* @return response in stream
* @throws IOException
* @throws ClientProtocolException
*/
public InputStream getStream() throws ClientProtocolException, IOException {

HttpEntity entity = httprequest();
InputStream ret = null;

if (entity != null) {
try {
byte[] b = EntityUtils.toByteArray(entity);
ret = new ByteArrayInputStream(b);
} finally {
release(entity);
}
}

return ret;
}

/**
* get "String" as response
*
* @return response in string
* @throws IOException
* @throws ClientProtocolException
*/
public String getString() throws ClientProtocolException, IOException {

HttpEntity entity = httprequest();
String ret = null;

if (entity != null) {
try {
ret = EntityUtils.toString(entity);
} finally {
release(entity);
}
}

return ret;
}

/**
* release connection resource
*
* @param entity
*/
private static void release(HttpEntity entity) {
try {
entity.consumeContent();
} catch (IOException e) {
e.printStackTrace();
}
}

/**
* get "HttpEntity" as response
*
* @return
* @throws IOException
* @throws ClientProtocolException
*/
private HttpEntity httprequest() throws ClientProtocolException,
IOException {

System.out.println(mUrl);

DefaultHttpClient client = null;
HttpEntity entity = null;

BasicHttpParams httpParameters = new BasicHttpParams();

if (mConfig != null) {
// set connection timeout
HttpConnectionParams.setConnectionTimeout(httpParameters,
mConfig.timeoutConnection);
}

client = new DefaultHttpClient(httpParameters);

DefaultHttpRequestRetryHandler retryHandler = new DefaultHttpRequestRetryHandler(
3, true);
client.setHttpRequestRetryHandler(retryHandler);

// set username & password if available
if (mConfig != null
&& !(isEmpty(mConfig.username) && isEmpty(mConfig.password))) {
AuthScope as = new AuthScope(mConfig.host, mConfig.port);
UsernamePasswordCredentials upc = new UsernamePasswordCredentials(
mConfig.username, mConfig.password);

client.getCredentialsProvider().setCredentials(as, upc);
}

// check get or post method by params
HttpRequestBase method = null;
if (mBody == null) {
method = new HttpGet(mUrl);
} else {
method = new HttpPost(mUrl);
((HttpPost) method).setEntity(mBody);
}

// set request header
if (mHeaders != null) {
Iterator<?> iter = mHeaders.entrySet().iterator();
while (iter.hasNext()) {
Map.Entry<?, ?> entry = (Entry<?, ?>) iter.next();
String key = (String) entry.getKey();
String val = (String) entry.getValue();
method.setHeader(key, val);
}
}

// get response
HttpResponse response = null;
if (mConfig == null || isEmpty(mConfig.host) || isEmpty(mConfig.scheme)) {
// only URL is available
response = client.execute(method);
} else {
BasicHttpContext localContext = new BasicHttpContext();

BasicScheme basicAuth = new BasicScheme();
localContext.setAttribute("preemptive-auth", basicAuth);

HttpHost targetHost = new HttpHost(mConfig.host, mConfig.port,
mConfig.scheme);

response = client.execute(targetHost, method, localContext);
}

mStatus = response.getStatusLine().getStatusCode();
entity = response.getEntity();

return entity;
}

/**
* Check the string is valuable or not
*
* @param s
* @return true if s is null or s.length() == 0 false otherwise
*/
private boolean isEmpty(String s) {
return s == null || s.length() == 0;
}
}

3. 调用
[b]GET请求[/b]

HttpRequest request = new HttpRequest("...");
request.execute();


UserAgentConfig config = new UserAgentConfig();
config.host = "...";
config.username = "...";
config.password = "...";

HttpRequest request = new HttpRequest("...");
request.setConfig(config);

System.out.println(request.getString());

[b]POST请求[/b]

HttpRequest request = new HttpRequest("...");
request.addHeader("...", "...");
request.setPostBody("....");
request.execute();

System.out.println(request.getStatusCode());
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值