Android:多线程的HttpClient

/*Addressing Multithreading Issues
The examples we’ve shown so far created a new HttpClient for each request. In
practice, however, you should probably create one HttpClient for the entire application
and use that for all of your HTTP communication. With one HttpClient servicing all of
your HTTP requests, you should also pay attention to multithreading issues that could
surface if you make simultaneous requests through the same HttpClient. Fortunately,
the HttpClient provides facilities that make this easy—all you have to do is create the
DefaultHttpClient using a ThreadSafeClientConnManager, as shown in Listing 11–6.*/
Listing 11–6. Creating an HttpClient for Multithreading: CustomHttpClient.java
import org.apache.http.HttpVersion;
import org.apache.http.client.HttpClient;
import org.apache.http.conn.ClientConnectionManager;
import org.apache.http.conn.params.ConnManagerParams;
import org.apache.http.conn.scheme.PlainSocketFactory;
import org.apache.http.conn.scheme.Scheme;
import org.apache.http.conn.scheme.SchemeRegistry;
import org.apache.http.conn.ssl.SSLSocketFactory;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.impl.conn.tsccm.ThreadSafeClientConnManager;
import org.apache.http.params.BasicHttpParams;
import org.apache.http.params.HttpConnectionParams;
import org.apache.http.params.HttpParams;
import org.apache.http.params.HttpProtocolParams;
import org.apache.http.protocol.HTTP;
public class CustomHttpClient {
private static HttpClient customHttpClient;
/** A private Constructor prevents instantiation */
private CustomHttpClient() {
}
public static synchronized HttpClient getHttpClient() {
if (customHttpClient == null) {
HttpParams params = new BasicHttpParams();
HttpProtocolParams.setVersion(params, HttpVersion.HTTP_1_1);
HttpProtocolParams.setContentCharset(params,
HTTP.DEFAULT_CONTENT_CHARSET);
HttpProtocolParams.setUseExpectContinue(params, true);
HttpProtocolParams.setUserAgent(params,
"Mozilla/5.0 (Linux; U; Android 2.2.1; en-us; Nexus One Build/FRG83) AppleWebKit/533.1
(KHTML, like Gecko) Version/4.0 Mobile Safari/533.1"
);
ConnManagerParams.setTimeout(params, 1000);
HttpConnectionParams.setConnectionTimeout(params, 5000);
HttpConnectionParams.setSoTimeout(params, 10000);
SchemeRegistry schReg = new SchemeRegistry();
schReg.register(new Scheme("http",
PlainSocketFactory.getSocketFactory(), 80));
schReg.register(new Scheme("https",
SSLSocketFactory.getSocketFactory(), 443));
ClientConnectionManager conMgr = new
ThreadSafeClientConnManager(params,schReg);
customHttpClient = new DefaultHttpClient(conMgr, params);
}
return customHttpClient;
}
public Object clone() throws CloneNotSupportedException {
throw new CloneNotSupportedException();
}
}
/**
If your application needs to make more than a few HTTP calls, you should create an
HttpClient that services all your HTTP requests. The simplest way to do this is to create
a singleton class that can be accessed from anywhere in the application, as we’ve
shown here. This is a fairly standard Java pattern in which we synchronize access to a
CHAPTER 11: Building and Consuming Services 317
getter method, and that getter method returns the one and only HttpClient object for
the singleton, creating it the first time as necessary.
Now, take a look at the getHttpClient() method of CustomHttpClient. This method is
responsible for creating our singleton HttpClient. We set some basic parameters, some
timeout values, and the schemes that our HttpClient will support (i.e., HTTP and
HTTPS). Notice that when we instantiate the DefaultHttpClient(), we pass in a
ClientConnectionManager. The ClientConnectionManager is responsible for managing
HTTP connections for the HttpClient. Because we want to use a single HttpClient for
all the HTTP requests (requests which could overlap if we're using threads), we create a
ThreadSafeClientConnManager.
We also show you a simpler way of collecting the response from the HTTP request,
using a BasicResponseHandler. The code for our activity that uses our CustomHttpClient
is in Listing 11–7.**/
Listing 11–7. Using Our CustomHttpClient: HttpActivity.java
import java.io.IOException;
import org.apache.http.client.HttpClient;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.impl.client.BasicResponseHandler;
import org.apache.http.params.HttpConnectionParams;
import org.apache.http.params.HttpParams;
import android.app.Activity;
import android.os.Bundle;
import android.util.Log;
public class HttpActivity extends Activity
{
private HttpClient httpClient;
@Override
public void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
httpClient = CustomHttpClient.getHttpClient();
getHttpContent();
}
public void getHttpContent()
{
try {
HttpGet request = new HttpGet("http://www.google.com/");
String page = httpClient.execute(request,
new BasicResponseHandler());
System.out.println(page);
} catch (IOException e) {
// covers:
// ClientProtocolException
// ConnectTimeoutException
// ConnectionPoolTimeoutException
// SocketTimeoutException
e.printStackTrace();
}
318 CHAPTER 11: Building and Consuming Services
}
}

For this sample application, we do a simple HTTP get of the Google home page. We
also use a BasicResponseHandler object to take care of rendering the page as a big
String, which we then write out to LogCat. As you can see, adding a
BasicResponseHandler to the execute() method is very easy to do.


  • 0
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
Android平台上实现多线程下载音乐可以通过以下步骤: 1. 首先,在AndroidManifest.xml文件中添加访问网络的权限。 2. 创建一个Service来执行下载任务,这样可以保证在活动销毁或离开前台时下载任务仍然可以继续。 3. 在Service中创建线程池,可以使用Java的Executor框架来实现,例如ThreadPoolExecutor。 4. 在要进行下载的Activity中,通过按钮点击或其他触发方式来启动Service,并传递音乐下载链接等参数。 5. 在Service的onStartCommand方法中,从传递过来的参数中获取音乐下载链接,然后根据需求将链接拆分为多个部分。 6. 使用多线程分别下载这些部分,每个线程可以使用Java的URLConnection或HttpClient等工具类库进行网络请求。 7. 下载完成后,将每个部分的数据合并为完整的音乐文件。 8. 在下载过程中,可以使用BroadcastReceiver来发送下载进度或状态的广播,然后在Activity中注册该广播接收器来更新UI界面。 9. 在下载过程中,可以通过判断当前网络状态来控制下载速度,例如在移动数据网络下可限制下载速度,而在WIFI网络下可充分利用带宽。 10. 需要注意的是,下载过程中要处理异常情况,例如网络中断、服务器异常等,可以使用try-catch块来捕获异常并进行相应的处理。 以上就是Android平台上实现多线程下载音乐的大致步骤,通过合理地利用多线程技术,可以加快下载速度,提升用户体验。

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值