android中Http和HttpClient的Get和Post方法的使用:
不要忘记添加网络请求权限
一,Http用Get方法请求数据:
1, 创建URL实例:URL url = new URL(“http://duduhali.sinaapp.com/Test/httpTest.php?name=duduhali&password=12345");
2, 获取URL连接:URLConnection connection = url.openConnection();
3,获取字节输入流:InputStream is = connection.getInputStream();
4,根据字节流生成字符流,并设置编码:InputStreamReader isr = new InputStreamReader(is,"utf-8");
5,创建字符流缓冲区:BufferedReader br = new BufferedReader(isr);
6,读取数据:while ((line = br.readLine()) != null) {
result.append(line);
}
7,分别关闭资源:br.close();
isr.close();
is.close();
代码如下:
new AsyncTask<String, Void, String>() {
@Override
protected String doInBackground(String... params) {
String line;
StringBuffer result = new StringBuffer();
try {
// 用的是Http的Get方法
URL url = new URL(params[0]);// 创建URL
URLConnection connection = url.openConnection();// 获取URL连接
InputStream is = connection.getInputStream();// 获取字节输入流
InputStreamReader isr = new InputStreamReader(is, "utf-8");// 根据字节流生成字符流,并设置编码
BufferedReader br = new BufferedReader(isr);// 创建字符流缓冲区
while ((line = br.readLine()) != null) {
result.append(line);
}
br.close();
isr.close();
is.close();
} catch (MalformedURLException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
return result.toString();
}
@Override
protected void onPostExecute(String result) {
// TODO Auto-generated method stub
tv.setText(result);// 显示数据
}
}.execute("http://duduhali.sinaapp.com/Test/httpTest.php?name=duduhali&password=12345");
二,Http用Post方法请求数据:
1,创建URL实例:URL url = new URL(params[0]);
2,获取URL链接并强制转换成子类HttpURL连接:HttpURLConnection connection = (HttpURLConnection) url.openConnection();
3,设置使用输出流和Post方法:connection.setDoOutput(true);// 设置使用输出流
connection.setRequestMethod("POST");// 默认为Get方法
//还可设置其它一些属性
4, 获取输出字节流并构建输出字符流,且设置编码:OutputStreamWriter osw = new OutputStreamWriter( connection.getOutputStream(), "utf-8");
5,创建输出缓冲区:BufferedWriter bw = new BufferedWriter(osw);
6,设置输出参数:bw.write("name=duduhali&password=12345");
7,刷新输出流:bw.flush();
8,获取输入字节流:InputStream is = connection.getInputStream();
9,创建输入字符流并设置编码:InputStreamReader isr = new InputStreamReader(is,"utf-8");//不设置编码有返回数据有中文时会出现乱码
10,创建输入缓冲区:BufferedReader br = new BufferedReader(isr);
11,读取网络返回数据:while ((line = br.readLine()) != null) {
result.append(line);
}
12,关闭输入流:br.close();
isr.close();
is.close();
代码如下:
new AsyncTask<String, Void, String>() {
@Override
protected String doInBackground(String... params) {
StringBuffer result = new StringBuffer();
try {
URL url = new URL(params[0]);
// 获取URL链接并强制转换成子类HttpURL连接,以便能够使用更多的API
HttpURLConnection connection = (HttpURLConnection) url
.openConnection();
connection.setDoInput(true);// 输入流默认就为开启状态,可不设
connection.setDoOutput(true);// 设置使用输出流
connection.setRequestMethod("POST");// 默认为Get方法
// connection.setUseCaches(false); // 设置是否使用缓存
// (如果不设此项,在传送序列化对象时,当WEB服务默认的不是这种类型时可能抛java.io.EOFException)
// connection.setRequestProperty("Content-type",
// "application/x-java-serialized-object");
// 获取输出字符流,并设置编码
OutputStreamWriter osw = new OutputStreamWriter(
connection.getOutputStream(), "utf-8");
BufferedWriter bw = new BufferedWriter(osw);
bw.write("name=duduhali&password=12345");// bw.write("a=A&b=B");
bw.flush();
InputStream is = connection.getInputStream();
InputStreamReader isr = new InputStreamReader(is, "utf-8");// 不设置编码有返回数据有中文时会出现乱码
BufferedReader br = new BufferedReader(isr);
String line;
while ((line = br.readLine()) != null) {
result.append(line);
}
br.close();
isr.close();
is.close();
} catch (MalformedURLException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
return result.toString();
}
@Override
protected void onPostExecute(String result) {
// TODO Auto-generated method stub
tv.setText(result);
}
}.execute("http://duduhali.sinaapp.com/Test/httpTest.php");
三,HttpClient用Get方法请求数据:
1,创建HttpClient对象:HttpClient client = new DefaultHttpClient();
2,创建请求方法的实例:HttpGet get = new HttpGet(urlString);
3,发送请求获取连接响应信息:HttpResponse response = client.execute(get);
4,获取HttpEntity实体:HttpEntity httpEntity = response.getEntity();
5,获取服务器返回信息:String value = EntityUtils.toString(httpEntity, "utf-8");
代码如下:
new AsyncTask<String, Void, String>() {
@Override
protected String doInBackground(String... arg0) {
String urlString = arg0[0];
HttpGet get = new HttpGet(urlString);// 创建请求方法的实例
try {
HttpResponse response = client.execute(get);// 获取连接响应信息
// 可以调用HttpResponse的getAllHeaders()、getHeaders(String
// name)等方法可获取服务器的响应头
HttpEntity httpEntity = response.getEntity();// 获取HttpEntity实体
// HttpEntity可以使流也可以是字符串,封装了一些对字符和流的操作,还有另外几种Entity实体类
// String value = EntityUtils.toString( httpEntity
// );//不加utf-8出现中文乱码
String value = EntityUtils.toString(httpEntity, "utf-8");
return value;
} 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) {
tv.setText(result);
}
}.execute("http://duduhali.sinaapp.com/Test/httpTest.php?name=duduhali&password=12345");
四,HttpClient用Post方法请求数据:
1,创建HttpClient对象:HttpClient client = new DefaultHttpClient();
2,创建请求方法的实例:HttpPost post = new HttpPost(arg0[0]);
3, 设置请求参数:
List<BasicNameValuePair> list = new ArrayList<BasicNameValuePair>();
list.add(new BasicNameValuePair("name", "duduhali"));
post.setEntity(new UrlEncodedFormEntity(list));
4,发送请求获取相应:HttpResponse response = client.execute(post);
5,获取HttpEntity实体:HttpEntity httpEntity = response.getEntity();
6,获取服务器返回信息:String value = EntityUtils.toString(httpEntity, "utf-8");
代码如下:new AsyncTask<String, Void, String>() {
@Override
protected String doInBackground(String... arg0) {
HttpPost post = new HttpPost(arg0[0]);// 创建请求方法的实例
try {
List<BasicNameValuePair> list = new ArrayList<BasicNameValuePair>();
list.add(new BasicNameValuePair("name", "duduhali"));
post.setEntity(new UrlEncodedFormEntity(list));// 设置请求参数
} catch (UnsupportedEncodingException e1) {
}
try {
HttpResponse response = client.execute(post);// 发送请求获取相应
HttpEntity httpEntity = response.getEntity();// 获取HttpEntity实体
// HttpEntity可以是流也可以是字符串,封装了一些对字符和流的操作,还有另外几种Entity实体类
// String value = EntityUtils.toString( httpEntity
// );//不加utf-8出现中文乱码
String value = EntityUtils.toString(httpEntity, "utf-8");
return value;
} 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) {
tv.setText(result);
}
}.execute("http://duduhali.sinaapp.com/Test/httpTest.php");
五,获取图片
代码如下:
new AsyncTask<String, Void, Bitmap>() {
@Override
protected Bitmap doInBackground(String... params) {
try {
URL url = new URL(params[0]);
HttpURLConnection conn = (HttpURLConnection) url
.openConnection();
conn.setRequestMethod("GET");
// setConnectTimeout:设置连接主机超时(单位:毫秒)
// setReadTimeout:设置从主机读取数据超时(单位:毫秒)
conn.setReadTimeout(5 * 1000);// 设置从主机读取超时时间为5秒
int code = conn.getResponseCode();// 获取请求码,不设置setReadTimeout可能阻塞线程
if (code == 200) {// 正常返回
InputStream inputStream = conn.getInputStream();// 获取字节流
Bitmap bitmap = BitmapFactory.decodeStream(inputStream);
return bitmap;
}
} catch (Exception e) {
e.printStackTrace();
}
return null;
}
@Override
protected void onPostExecute(Bitmap result) {
// TODO Auto-generated method stub
if (result != null) {
tv.setBackground(new BitmapDrawable(result));
}
}
}.execute("https://www.baidu.com/img/bd_logo1.png");