用的是apache httpClient:
首先,记得在AndroidManifest.xml中添加网络请求的权限:
<uses-permission android:name="android.permission.INTERNET"></uses-permission>
get请求:
1.HttpClient client = new DefaultHttpClient();
2.HttpGet get = new HttpGet(url);
3.HttpResponse response = client.execute(get);
4.HttpEntity entity = response.getEntity();
5.InputStream inputStream = entity.getContent();
代码如下:
package com.example.httpgettest;
import java.io.BufferedReader;
import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.net.MalformedURLException;
import java.net.URI;
import java.net.URISyntaxException;
import java.net.URL;
import javax.net.ssl.HttpsURLConnection;
import org.apache.http.*;
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 android.os.AsyncTask;
import android.os.Bundle;
import android.app.Activity;
import android.view.Menu;
import android.view.TextureView;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.TextView;
public class MainActivity extends Activity {
private TextView textView;
private Button button;
private String resultString = "";
private String urlString ;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
textView = (TextView)findViewById(R.id.text_view);
button = (Button)findViewById(R.id.button);
button.setOnClickListener(new OnClickListener() {
@Override
public void onClick(View v) {
// TODO Auto-generated method stub
Down down = new Down();
urlString = "http://www.baidu.com";
down.execute(urlString);
}
});
}
@Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.main, menu);
return true;
}
class Down extends AsyncTask<String, Integer, String>{
@Override
protected String doInBackground(String... params) {
// TODO Auto-generated method stub
try {
HttpClient client = new DefaultHttpClient();
HttpGet get = new HttpGet(params[0]);
HttpResponse response = client.execute(get);
if (response.getStatusLine().getStatusCode() == HttpStatus.SC_OK) {
HttpEntity entity = response.getEntity();
InputStream inputStream = entity.getContent();
InputStreamReader inputStreamReader = new InputStreamReader(inputStream);
BufferedReader in = new BufferedReader(inputStreamReader);
String inputLine="";
while((inputLine=in.readLine())!=null){
resultString+=inputLine+"\n";
}
return resultString;
}
} catch (ClientProtocolException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
return null;
}
@Override
protected void onPostExecute(String result) {
// TODO Auto-generated method stub
super.onPostExecute(result);
textView.setText(result);
}
//onPreExecute方法用于在执行后台任务前做一些UI操作
@Override
protected void onPreExecute() {
textView.setText("loading...");
}
}
}
<span style="font-family:Microsoft YaHei;"><?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
package="com.example.httpgettest"
android:versionCode="1"
android:versionName="1.0" >
<uses-permission android:name="android.permission.INTERNET"></uses-permission>
<uses-sdk
android:minSdkVersion="8"
android:targetSdkVersion="15" />
<application
android:allowBackup="true"
android:icon="@drawable/ic_launcher"
android:label="@string/app_name"
android:theme="@style/AppTheme" >
<activity
android:name=".MainActivity"
android:label="@string/app_name" >
<intent-filter>
<action android:name="android.intent.action.MAIN" />
<category android:name="android.intent.category.LAUNCHER" />
</intent-filter>
</activity>
</application>
</manifest>
</span>
<span style="font-family:Microsoft YaHei;"><RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:paddingBottom="@dimen/activity_vertical_margin"
android:paddingLeft="@dimen/activity_horizontal_margin"
android:paddingRight="@dimen/activity_horizontal_margin"
android:paddingTop="@dimen/activity_vertical_margin"
tools:context=".MainActivity" >
<Button android:id="@+id/button"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:text="httpGet"></Button>
<TextView android:id="@+id/text_view"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:layout_below="@id/button"
android:textSize="20sp"
android:textColor="@android:color/darker_gray"
android:scrollbars="vertical"/>
</RelativeLayout>
</span>
post请求:
1.HttpClient httpClient = new DefaultHttpClient();
2.HttpPost httpPost = new HttpPost(url);
3.List<NameValuePair>HttpEntity httpEntity = new UrlEncodedFormEntity(entityList); entityList = new ArrayList<NameValuePair>();
4.httpPost.setEntity(httpEntity);
5.HttpResponse response = httpClient.execute(httpPost);
6.InputStream inputStream = response.getEntity().getContent();
代码如下:
<span style="font-family:Microsoft YaHei;">package com.example.httpposttest;
import java.io.BufferedReader;
import java.io.ByteArrayOutputStream;
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.UnsupportedEncodingException;
import java.util.ArrayList;
import java.util.List;
import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.NameValuePair;
import org.apache.http.client.ClientProtocolException;
import org.apache.http.client.HttpClient;
import org.apache.http.client.entity.UrlEncodedFormEntity;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.impl.conn.DefaultClientConnection;
import org.apache.http.message.BasicNameValuePair;
import android.os.AsyncTask;
import android.os.Bundle;
import android.os.Environment;
import android.app.Activity;
import android.view.Menu;
import android.view.View;
import android.widget.ArrayAdapter;
import android.widget.Button;
import android.widget.ProgressBar;
import android.widget.TextView;
public class MainActivity extends Activity {
private Button button;
private TextView textView;
private ProgressBar progressBar;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
button = (Button)findViewById(R.id.button);
textView = (TextView)findViewById(R.id.text_view);
progressBar = (ProgressBar)findViewById(R.id.progress_bar);
button.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
// TODO Auto-generated method stub
HttpPostAsy post = new HttpPostAsy();
post.execute("http://www.baidu.com");
}
});
}
class HttpPostAsy extends AsyncTask<String, Integer, String>{
@Override
protected void onProgressUpdate(Integer... values) {
// TODO Auto-generated method stub
super.onProgressUpdate(values);
if(values[0] == 100){
progressBar.setVisibility(View.GONE);
}else {
progressBar.setProgress(values[0]);
}
}
@Override
protected void onPreExecute() {
// TODO Auto-generated method stub
super.onPreExecute();
textView.setText("loading...");
}
@Override
protected void onPostExecute(String result) {
// TODO Auto-generated method stub
super.onPostExecute(result);
textView.setText(result);
}
@Override
protected String doInBackground(String... params) {
// TODO Auto-generated method stub
HttpClient httpClient = new DefaultHttpClient();
HttpPost httpPost = new HttpPost(params[0]);
List<NameValuePair> entityList = new ArrayList<NameValuePair>();
// entityList.add( new BasicNameValuePair("username", ""));
try {
HttpEntity httpEntity = new UrlEncodedFormEntity(entityList);
httpPost.setEntity(httpEntity);
HttpResponse response = httpClient.execute(httpPost);
if (null == response)
{
return "null";
}
long totallength = response.getEntity().getContentLength();
InputStream inputStream = response.getEntity().getContent();
String filePath = null;
boolean hasSDCard = Environment.getExternalStorageState().equals(Environment.MEDIA_MOUNTED);
if (hasSDCard) {
System.out.println("*do not have sd card*");
filePath = Environment.getExternalStorageDirectory().toString() + File.separator + "a.txt";
} else {
filePath = Environment.getDownloadCacheDirectory().toString() + File.separator + "a.txt";
}
File file = new File(filePath);
if(!file.exists()){
System.out.println("*file not exist*");
File pFile = file.getParentFile();
pFile.mkdirs();
file.createNewFile();
}
ByteArrayOutputStream byteArrayOutputStream = new ByteArrayOutputStream();
FileOutputStream fileOutputStream = new FileOutputStream(file);
byte[] buffer = new byte[1024];
String result = "";
String line = "";
int count = 0;
int length = -1;
while ((length=inputStream.read(buffer))!=-1)
{
byteArrayOutputStream.write(buffer, 0, length);
fileOutputStream.write(buffer);
count = count +length;
publishProgress((int) ((count / (float) totallength) * 100));
for (int i = 0; i < buffer.length; i++) {
result = result + buffer[i];
}
}
return result;
} catch (UnsupportedEncodingException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (ClientProtocolException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
return "null";
}
}
@Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.main, menu);
return true;
}
}
</span>
<span style="font-family:Microsoft YaHei;"><RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:paddingBottom="@dimen/activity_vertical_margin"
android:paddingLeft="@dimen/activity_horizontal_margin"
android:paddingRight="@dimen/activity_horizontal_margin"
android:paddingTop="@dimen/activity_vertical_margin"
tools:context=".MainActivity" >
<Button android:id="@+id/button"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:text="httpPost"/>
<ProgressBar android:id="@+id/progress_bar"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:layout_below="@id/button"
style="?android:attr/progressBarStyleHorizontal" />
<ScrollView android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:layout_below="@id/progress_bar">
<TextView android:id="@+id/text_view"
android:layout_width="fill_parent"
android:layout_height="wrap_content"/>
</ScrollView>
</RelativeLayout>
</span>