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;
}
}
}