Android应用经常会和服务器端交互,这就需要手机客户端发送网络请求,下面介绍四种常用网络请求方式,我这边是通过Android单元测试来完成这四种方法的,还不清楚Android的单元测试的同学们请看Android开发技巧总结中的Android单元测试的步骤一文。
Get方式:
// Get方式请求
public static void requestByGet() throws Exception {
String path = "https://reg.163.com/logins.jsp?id=helloworld&pwd=android";
// 新建一个URL对象
URL url = new URL(path);
// 打开一个HttpURLConnection连接
HttpURLConnection urlConn = (HttpURLConnection) url.openConnection();
// 设置连接超时时间
urlConn.setConnectTimeout(5 * 1000);
// 开始连接
urlConn.connect();
// 判断请求是否成功
if (urlConn.getResponseCode() == HTTP_200) {
// 获取返回的数据
byte[] data = readStream(urlConn.getInputStream());
Log.i(TAG_GET, "Get方式请求成功,返回数据如下:");
Log.i(TAG_GET, new String(data, "UTF-8"));
} else {
Log.i(TAG_GET, "Get方式请求失败");
}
// 关闭连接
urlConn.disconnect();
}
Post方式:
// Post方式请求
public static void requestByPost() throws Throwable {
String path = "http://v.juhe.cn/toutiao/index";
// 请求的参数转换为byte数组
String params = "tyde="+URLEncoder.encode("yule","UTF-8")+"&key="+"608b9fa8caf0b6dc08b9bc4caf7892f8";
byte[] postData = params.getBytes();
// 新建一个URL对象
URL url = new URL(path);
// 打开一个HttpURLConnection连接
HttpURLConnection urlConn = (HttpURLConnection) url.openConnection();
// 设置连接超时时间
urlConn.setConnectTimeout(5 * 1000);
// Post请求必须设置允许输出
urlConn.setDoOutput(true);
// Post请求不能使用缓存
urlConn.setUseCaches(false);
// 设置为Post请求
urlConn.setRequestMethod("POST");
urlConn.setInstanceFollowRedirects(true);
// 配置请求Content-Type
urlConn.setRequestProperty("Content-Type",
"application/x-www-form-urlencode");
// 开始连接
urlConn.connect();
// 发送请求参数
DataOutputStream dos = new DataOutputStream(urlConn.getOutputStream());
dos.write(postData);
dos.flush();
dos.close();
// 判断请求是否成功
if (urlConn.getResponseCode() == HTTP_200) {
InputStream is = http.getInputStream();
byte[] by=new byte[1024];
int i=0;
StringBuffer sb=new StringBuffer();
while ((i=is.read(by))!=-1) {
Log.i("log",new String(by,0,i));
}
} else {
Log.i(TAG_POST, "Post方式请求失败");
}
}
下载图片:
public class MainActivity extends Activity {
private Button mBtn;
private ImageView mImg;
private String urlstr = "http://img4q.duitang.com/uploads/item/201502/13/20150213134559_2aAdz.thumb.700_0.jpeg";
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
initView();
}
private Handler handler = new Handler(){
@Override
public void handleMessage(Message msg) {
// TODO Auto-generated method stub
super.handleMessage(msg);
if (msg.what == 1) {
Bitmap bit = (Bitmap) msg.obj;
mImg.setImageBitmap(bit);
}
}
};
private void initView() {
mBtn = (Button) findViewById(R.id.mBtn);
mImg = (ImageView) findViewById(R.id.mImg);
mBtn.setOnClickListener(new OnClickListener() {
@Override
public void onClick(View v) {
new Thread(new Runnable() {
@Override
public void run() {
// TODO Auto-generated method stub
try {
/*URL url = new URL(urlstr);
//打开连接
HttpURLConnection conn = (HttpURLConnection) url.openConnection();
//设置联网超时时间
conn.setConnectTimeout(30*1000);
//设置读取时间
conn.setReadTimeout(60*1000);
conn.setDoInput(true);
conn.setDoOutput(true);
//设置请求方法为get
conn.setRequestMethod("GET");
//得到输入流
InputStream is = conn.getInputStream();
//缓冲输入流
BufferedInputStream bis = new BufferedInputStream(is);
//得到内部SD卡存储路径
String path = Environment.getExternalStorageDirectory() + "/meinv.jpg";
File file = new File(path);
//缓冲输出流,(遍历输入流添加到输出流中)把图片存进SD卡内
BufferedOutputStream bos = new BufferedOutputStream(new FileOutputStream(file));
byte[] by = new byte[8*1024];
int len = 0;
while ((len = bis.read(by))!= -1) {
bos.write(by, 0, len);
}
bos.flush();
bos.close();
bis.close();
is.close();
Bitmap bitmap = BitmapFactory.decodeFile(path);*/
//直接下载图片设置到布局上
URL urll = new URL(urlstr);
HttpURLConnection connn=(HttpURLConnection)urll.openConnection();
connn.setDoInput(true);
/*connn.connect();*/
InputStream iss =connn.getInputStream();
//缓冲输入流
BufferedInputStream bis = new BufferedInputStream(iss);
Bitmap bitmap=BitmapFactory.decodeStream(bis);
iss.close();
Message msg = new Message();
msg.what = 1;
msg.obj = bitmap;
handler.sendMessage(msg);
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}).start();
}
});
}
}