HttpConnection
HttpClient 是一个接口,因此无法创建它的实例,通常情况下都会创建一个DefaultHttpClient的实例,如下:
HttpClient client=new DefaultHttpClient();//生成client方法;
DoGet
接下来就是发起一条Get请求,就可以创建一个HttpGet对象,并传入目标网络地址,然后调用HttpClient的execute()方法即可
HttpGet get=new HttpGet(stringurl);//设置为get方法;
client.execute(get);
DoPost
发出一个DoPost请求
HttpPost post=new HttpPost(urlString);
通过一个NameValuePair()集合来存放待提交的参数,并将这个参数集合传入到一个UrlEncodedFormEntity中,然后调用HttpPost的setEntity()方法将构建好的UrlEncodedFormEntity传入,如下:
NameValuePair pair1=new BasicNameValuePair("username","ZHANGSAN");
NameValuePair pair2=new BasicNameValuePair("password","1234");
ArrayList<NameValuePair> list=new ArrayList<NameValuePair>();
list.add(pair1);
list.add(pair2);
post.setEntity(new UrlEncodedFormEntity(list, "UTF-8"));
post.setHeader("Content-Type", "application/x-www-form-urlencoded; charset=UTF-8");
最后执行HttoClient的execute()方法
myDopostTask.execute();
由于需要连接网络,需要读写权限AndroidManifest.xml修改如下:
<uses-permission android:name="ANDROID.PERMISSION.INTERNET"></uses-permission>
<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE"></uses-permission>
<uses-permission android:name="android.permission.READ_EXTERNAL_STORAGE"></uses-permission>
activity_main.xml
<LinearLayout 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:orientation="vertical"
tools:context=".MainActivity">
<Button
android:id="@+id/btn_get"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="HttpClientGet"/>
<Button
android:id="@+id/btn_post"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="HttpClientPost"/>
</LinearLayout>
MainActivity.java
public class MainActivity extends AppCompatActivity implements View.OnClickListener{
private Button btn_get;
private Button btn_post;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
btn_get= (Button) findViewById(R.id.btn_get);
btn_post= (Button) findViewById(R.id.btn_post);
btn_get.setOnClickListener(this);
btn_post.setOnClickListener(this);
}
@Override
public void onClick(View v) {
switch(v.getId()){
case R.id.btn_get:
MyDogetTask myDogetTask=new MyDogetTask();
myDogetTask.execute();
break;
case R.id.btn_post:
MyDopostTask myDopostTask=new MyDopostTask();
myDopostTask.execute();
break;
default :
break;
}
}
class MyDogetTask extends AsyncTask<String,String,String> {
@Override
protected void onPreExecute() {
super.onPreExecute();
}
@Override
protected void onPostExecute(String s) {
super.onPostExecute(s);
}
@Override
protected void onProgressUpdate(String... values) {
super.onProgressUpdate(values);
}
@Override
protected String doInBackground(String... strings) {
String urlString="http://http://192.168.0.82:8080/MyServerTest/MyTestServerlet?username=lisi&password=123456";
HttpClient client=new DefaultHttpClient();
HttpGet get=new HttpGet(urlString);//设置为get方法
//设置服务器接收后数据的读取方式为utf8
get.setHeader("Content-Type", "application/x-www-form-urlencoded; charset=UTF-8");
try {
HttpResponse response = client.execute(get);//执行get方法得到服务器的返回的所有数据都在response中
StatusLine statusLine=response.getStatusLine();//httpClient访问服务器返回的表头,包含http状态码
int code=statusLine.getStatusCode();//得到状态码
System.out.println("状态码为:"+code);
if(code== HttpURLConnection.HTTP_OK){
HttpEntity entity=response.getEntity();//得到数据的实体
InputStream is=entity.getContent();//得到输入流
BufferedReader br=new BufferedReader(new InputStreamReader(is));
String line=br.readLine();
while(line!=null){
System.out.println(line);
line=br.readLine();
}
}
} catch (ClientProtocolException e1) {
e1.printStackTrace();
} catch (IOException e1) {
e1.printStackTrace();
}
return null;
}
}
class MyDopostTask extends AsyncTask<String,String,String>{
@Override
protected void onPostExecute(String s) {
super.onPostExecute(s);
}
@Override
protected void onPreExecute() {
super.onPreExecute();
}
@Override
protected void onProgressUpdate(String... values) {
super.onProgressUpdate(values);
}
@Override
protected String doInBackground(String... strings) {
String urlString="http://http://192.168.0.82:8080/MyServerTest/MyTestServerlet";
HttpClient client=new DefaultHttpClient();
HttpPost post=new HttpPost(urlString);
NameValuePair pair1=new BasicNameValuePair("username","ZHANGSAN");
NameValuePair pair2=new BasicNameValuePair("password","1234");
ArrayList<NameValuePair> list=new ArrayList<NameValuePair>();
list.add(pair1);
list.add(pair2);
try {
post.setEntity(new UrlEncodedFormEntity(list, "UTF-8"));
post.setHeader("Content-Type", "application/x-www-form-urlencoded; charset=UTF-8");
HttpResponse response=client.execute(post);
int code=response.getStatusLine().getStatusCode();
if(code==HttpURLConnection.HTTP_OK){
HttpEntity entity=response.getEntity();
InputStream is=entity.getContent();
BufferedReader br=new BufferedReader(new InputStreamReader(is));
String line=br.readLine();
while(line!=null){
System.out.println(line);
line=br.readLine();
}
}
} catch (UnsupportedEncodingException e1) {
e1.printStackTrace();
} catch (ClientProtocolException e1) {
e1.printStackTrace();
} catch (IOException e1) {
e1.printStackTrace();
}
return null;
}
}
}
Vollet
在使用Volley之前需导入
eu.the4thfloor.volley:com.android.volley:2015.05.28这个包,导包可以有两种方法
1,按照顺序找到第4 处直接输入
eu.the4thfloor.volley:com.android.volley:2015.05.28找到jar包进行下载即可
2、从网上下载jar包,复制到libs包下,再在导进来进行了
Volley的机制图
MainActivity(单例设计目的:每次请求时都生成同一个消息请求队列,而没有必要每次请求都生成一个新的消息队列,)
activity_volley.xml
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:orientation="vertical" android:layout_width="match_parent"
android:layout_height="match_parent">
<LinearLayout
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:orientation="horizontal">
<Button
android:id="@+id/btn_volley"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="volley"/>
<Button
android:id="@+id/button_networkimage"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="NetWorkImage"/>
</LinearLayout>
<ScrollView
android:layout_width="match_parent"
android:layout_height="wrap_content">
<com.android.volley.toolbox.NetworkImageView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:id="@+id/networkimage"/>
</ScrollView>
<ScrollView
android:layout_width="match_parent"
android:layout_height="wrap_content">
<TextView
android:id="@+id/text_volley"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:text="Volley内容"/>
</ScrollView>
</LinearLayout>
VolleyActivity.java
public class VolleyActivity extends AppCompatActivity implements View.OnClickListener{
private TextView text_volley;
private Button btn_volley;
private Button btn_networkimage;
private NetworkImageView networkImageView;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_volley);
btn_volley= (Button) findViewById(R.id.btn_volley);
btn_volley.setOnClickListener(this);
text_volley= (TextView) findViewById(R.id.text_volley);
btn_networkimage= (Button) findViewById(R.id.button_networkimage);
btn_networkimage.setOnClickListener(this);
networkImageView= (NetworkImageView) findViewById(R.id.networkimage);
}
@Override
public void onClick(View v) {
switch(v.getId()){
case R.id.button_networkimage:
networkImageView.setImageUrl("http://img3.imgtn.bdimg.com/it/u=2975755759,394391192&fm=23&gp=0.jpg", MySingleton.getInstance(this).getImageLoader());
networkImageView.setImageUrl("http://www.daxueit.com/upload/201408/13/101047281001237.png", MySingleton.getInstance(this).getImageLoader());
break;
case R.id.btn_volley:
RequestQueue queue=Volley.newRequestQueue(getApplicationContext());
// StringRequest request=new StringRequest(Request.Method.GET, "http://192.168.0.30:8080/MyWebTest/MyTestServerlet", new Response.Listener<String>(){
StringRequest request=new StringRequest(Request.Method.GET, "http://192.168.0.82:8080/MyServersTest", new Response.Listener<String>(){
// StringRequest request=new StringRequest(Request.Method.GET, "http://www.360.com", new Response.Listener<String>(){
// StringRequest request=new StringRequest(Request.Method.POST, "http://192.168.0.30:8080/MyWebTest/MyTestServerlet", new Response.Listener<String>(){
@Override
public void onResponse(String response) {
text_volley.setText(response);}
},new ErrorListener() {
@Override
public void onErrorResponse(VolleyError error) {
text_volley.setText("网络连接错误");
}
}) {
// }){
// @Override
// protected Map<String, String> getParams() throws AuthFailureError {
// HashMap<String,String>map=new HashMap<>();
// map.put("username","lisiwang");
// return map;
// }
// };
};
// queue.add(request);
MySingleton.getInstance(getApplicationContext()).addToRequestQueue(request);
break;
}
MySingleton.java
public class MySingleton {
private static MySingleton mInstance;
private RequestQueue mRequestQueue;
private ImageLoader mImageLoader;
private static Context mCtx;
private MySingleton(Context context) {
mCtx = context;
mRequestQueue = getRequestQueue();
mImageLoader = new ImageLoader(mRequestQueue,
new ImageLoader.ImageCache() {
private final LruCache<String, Bitmap>
cache = new LruCache<String, Bitmap>(20);
@Override
public Bitmap getBitmap(String url) {
return cache.get(url);
}
@Override
public void putBitmap(String url, Bitmap bitmap) {
cache.put(url, bitmap);
}
});
}
public static synchronized MySingleton getInstance(Context context) {
if (mInstance == null) {
mInstance = new MySingleton(context);
}
return mInstance;
}
public RequestQueue getRequestQueue() {
if (mRequestQueue == null) {
// getApplicationContext() is key, it keeps you from leaking the
// Activity or BroadcastReceiver if someone passes one in.
mRequestQueue = Volley.newRequestQueue(mCtx.getApplicationContext());
}
return mRequestQueue;
}
public <T> void addToRequestQueue(Request<T> req) {
getRequestQueue().add(req);
}
public ImageLoader getImageLoader() {
return mImageLoader;
}
}
xUtils
activity_xutils.xml
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:orientation="vertical" android:layout_width="match_parent"
android:layout_height="match_parent">
<LinearLayout
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:orientation="horizontal">
<Button
android:id="@+id/btn_xutils_get"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Get网络内容"/>
<Button
android:id="@+id/btn_xutils_post"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Post网络内容"/>
</LinearLayout>
<ScrollView
android:layout_width="match_parent"
android:layout_height="wrap_content">
<TextView
android:id="@+id/text_xutils"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:text="xutils内容"/>
</ScrollView>
</LinearLayout>
XutilsActivity.java
public class XutilsActivity extends Activity implements View.OnClickListener{
@ViewInject(R.id.btn_xutils_get)
private Button button_get;
@ViewInject(R.id.text_xutils)
private TextView text_xutils;
@ViewInject(R.id.btn_xutils_post)
private Button button_post;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_xutils);
com.lidroid.xutils.ViewUtils.inject(this);
// button_get = (Button) findViewById(R.id.btn_xutils_get);
// button_get.setOnClickListener(this);
// button_post= (Button) findViewById(R.id.btn_xutils_post);
// button_post.setOnClickListener(this);
// text_xutils= (TextView) findViewById(R.id.text_xutils);
}
@OnClick({R.id.btn_xutils_get,R.id.btn_xutils_post})
@Override
public void onClick(View v) {
switch(v.getId()){
case R.id.btn_xutils_post:
HttpUtils clientPost=new HttpUtils();
RequestParams params=new RequestParams();
params.addBodyParameter("username","xutilspost");
clientPost.send(HttpRequest.HttpMethod.POST, "http://192.168.0.82:8080/MyServersTest", params, new RequestCallBack<String>()
// clientPost.send(HttpRequest.HttpMethod.POST, "http://192.168.0.30:8080/MyWebTest/MyTestServerlet", params, new RequestCallBack<String>()
{
@Override
public void onSuccess(ResponseInfo<String> responseInfo) {
text_xutils.setText(responseInfo.result);
}
@Override
public void onFailure(HttpException e, String s) {
text_xutils.setText("网络连接错误");
}
});
break;
case R.id.btn_xutils_get:
HttpUtils clientGet=new HttpUtils();
clientGet.send(HttpRequest.HttpMethod.GET, "http://www.360.com", new RequestCallBack<String>() {
@Override
public void onSuccess(ResponseInfo<String> responseInfo) {
text_xutils.setText(responseInfo.result);
}
@Override
public void onFailure(HttpException e, String s) {
text_xutils.setText("网络连接错误");
}
});
break;
}
}
}