Android应用经常会和服务器端交互,这就需要手机客户端发送网络请求,下面介绍四种常用网络请求方式,我这边是通过Android单元测试来完成这四种方法的,还不清楚Android的单元测试的同学们请看Android开发技巧总结中的Android单元测试的步骤一文。
Get方式:
public static void requestByGet()
throws Exception {
String path =
"https://reg.163.com/logins.jsp?id=helloworld&pwd=android";
URL url =
new URL(path);
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方式:
public static void requestByPost() throws Throwable {
String path =
"http://v.juhe.cn/toutiao/index";
String
params =
"tyde="+URLEncoder.encode(
"yule",
"UTF-8")+
"&key="+
"608b9fa8caf0b6dc08b9bc4caf7892f8";
byte[] postData =
params.getBytes();
URL url =
new URL(path);
HttpURLConnection urlConn = (HttpURLConnection) url.openConnection();
urlConn.setConnectTimeout(
5 *
1000);
urlConn.setDoOutput(
true);
urlConn.setUseCaches(
false);
urlConn.setRequestMethod(
"POST");
urlConn.setInstanceFollowRedirects(
true);
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) {
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() {
try {
URL urll =
new URL(urlstr);
HttpURLConnection connn=(HttpURLConnection)urll.openConnection();
connn.setDoInput(
true);
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) {
e.printStackTrace();
}
}
}).start();
}
});
}
}
转载请注明原文地址: https://ju.6miu.com/read-962.html