Android DownloadDemo 下載的一個範例

來源:互聯網
上載者:User

調了很久的Demo終於可以用了:

main.xml:

<?xml version="1.0" encoding="utf-8"?><LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"    android:layout_width="fill_parent"    android:layout_height="fill_parent"    android:orientation="vertical" >    <Button        android:id="@+id/downText"        android:layout_width="wrap_content"        android:layout_height="wrap_content"        android:text="下載文字檔" />    <EditText        android:id="@+id/editText1"        android:layout_width="300dip"        android:layout_height="200dip"        android:inputType="textMultiLine" >        <requestFocus />    </EditText></LinearLayout>

主DownDemoActivity:

package com.wangxin;import android.app.Activity;import android.os.Bundle;import android.view.View;import android.view.View.OnClickListener;import android.widget.Button;import android.widget.EditText;public class DownDemoActivity extends Activity {/** Called when the activity is first created. */public EditText et = null;private Button button = null;@Overridepublic void onCreate(Bundle savedInstanceState) {super.onCreate(savedInstanceState);setContentView(R.layout.main);button = (Button) findViewById(R.id.downText);et = (EditText) findViewById(R.id.editText1);button.setOnClickListener(new Button.OnClickListener() {@Overridepublic void onClick(View v) {// TODO Auto-generated method stub/* * Thread thread = new Thread(new DownThread()); thread.start(); */HttpDownLoader downloader = new HttpDownLoader();String lrc = downloader.HttpGet("http://lrc.bzmtv.com/lrc_db/2011-11-4-JNDSFNKOIOOJOCQQRMPOPI4-179511.lrc");et.setText(lrc);}});}}

下載工具類HttpDownLoader

package com.wangxin;import java.io.FileOutputStream;import java.io.InputStream;import java.io.UnsupportedEncodingException;import java.net.URL;import java.net.URLConnection;import org.apache.http.HttpResponse;import org.apache.http.client.methods.HttpGet;import org.apache.http.client.methods.HttpPost;import org.apache.http.entity.ByteArrayEntity;import org.apache.http.entity.StringEntity;import org.apache.http.impl.client.DefaultHttpClient;import org.apache.http.params.CoreConnectionPNames;import org.apache.http.util.EntityUtils;public class HttpDownLoader {private final static String Charset = "utf-8";public static String HttpGet(String url) {String res = null;try {DefaultHttpClient httpClient = new DefaultHttpClient();HttpGet httpRequest = new HttpGet(url);httpClient.getParams().setParameter(CoreConnectionPNames.CONNECTION_TIMEOUT, 5000);HttpResponse httpResponse = httpClient.execute(httpRequest);if (httpResponse.getStatusLine().getStatusCode() == 200) {res = EntityUtils.toString(httpResponse.getEntity(), Charset);}} catch (Exception e) {e.printStackTrace();}return FormatStr(res) ;}public static String HttpPost(String url, String data) {String res = null;try {HttpPost httpRequest = new HttpPost(url);httpRequest.setHeader("Content-Type","application/x-www-form-urlencoded");httpRequest.setEntity(new StringEntity(data, Charset));DefaultHttpClient httpClient = new DefaultHttpClient();httpClient.getParams().setParameter(CoreConnectionPNames.CONNECTION_TIMEOUT, 5000);HttpResponse httpResponse = httpClient.execute(httpRequest);if (httpResponse.getStatusLine().getStatusCode() == 200) {res = EntityUtils.toString(httpResponse.getEntity(), Charset);}} catch (Exception e) {e.printStackTrace();}return res;}public static String HttpPost(String url, byte[] data) {String res = null;try {HttpPost httpRequest = new HttpPost(url);httpRequest.setEntity(new ByteArrayEntity(data));DefaultHttpClient httpClient = new DefaultHttpClient();httpClient.getParams().setParameter(CoreConnectionPNames.CONNECTION_TIMEOUT, 5000);HttpResponse httpResponse = httpClient.execute(httpRequest);if (httpResponse.getStatusLine().getStatusCode() == 200) {res = EntityUtils.toString(httpResponse.getEntity());}} catch (Exception e) {e.printStackTrace();}return res;}public static boolean HttpDownload(String url, String savePath) {boolean res = false;try {URL sourceUrl = new URL(url);URLConnection conn = sourceUrl.openConnection();InputStream inputStream = conn.getInputStream();int fileSize = conn.getContentLength();FileOutputStream outputStream = new FileOutputStream(savePath);byte[] buffer = new byte[1024];int downSize = 0;int readLen = 0;while (downSize < fileSize && readLen != -1) {readLen = inputStream.read(buffer);if (readLen > -1) {outputStream.write(buffer, 0, readLen);downSize = downSize + readLen;}}outputStream.close();res = true;} catch (Exception e) {e.printStackTrace();}return res;}public static String HttpSOAP(String url, String action, String message) {String res = null;try {HttpPost httpRequest = new HttpPost(url);httpRequest.setHeader("Content-Type", "text/xml; charset="+ Charset);httpRequest.setHeader("SOAPAction", action);httpRequest.setEntity(new StringEntity(message, Charset));DefaultHttpClient httpClient = new DefaultHttpClient();httpClient.getParams().setParameter(CoreConnectionPNames.CONNECTION_TIMEOUT, 5000);HttpResponse httpResponse = httpClient.execute(httpRequest);if (httpResponse.getStatusLine().getStatusCode() == 200) {res = EntityUtils.toString(httpResponse.getEntity(), Charset);}} catch (Exception e) {e.printStackTrace();}return res;}public static String FormatStr(String str) {if (str == null || str.length() == 0) {return "";}try {return new String(str.getBytes("utf-8"), "gb2312");} catch (UnsupportedEncodingException e) {// TODO Auto-generated catch blocke.printStackTrace();return str;}}}
相關文章

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.