关闭

HttpConnection及Apache HttpClient的一些常见用法的demo

172人阅读 评论(0) 收藏 举报

客服端的代码:我先在XML里布局了几个简单的按钮,每个按钮代表一个方法事件,如下XML代码:

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:orientation="vertical" >
<TextView
   android:id="@+id/http_show_message_txt"
   android:layout_width="wrap_content"
   android:layout_height="wrap_content" />
<Button
        android:id="@+id/http_connect_btn"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:text="连接服务端" />
    <Button
        android:id="@+id/http_connect_get_btn"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:text="Get传参" />
    
    <Button
        android:id="@+id/http_connect_post_btn"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:text="Post传参" />
     <Button
        android:id="@+id/http_apache_client_btn"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:text="ApacheHttpClient传参" />
     <Button
        android:id="@+id/http_apache_client_get_btn"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:text="ApacheHttpClient_Get传参" />
       <Button
        android:id="@+id/http_apache_client_post_btn"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:text="ApacheHttpClient_Post传参" />
       
       <Button
        android:id="@+id/http_apache_client_fengzhuang_btn"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:text="封装工具类实现参数网络传递" />  

</LinearLayout>

接下来我定义了客服端的业务代码:

package com.scxh.android1503.ui.http;


import java.io.BufferedReader;
import java.io.File;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.OutputStream;
import java.io.PrintWriter;
import java.io.UnsupportedEncodingException;
import java.net.HttpURLConnection;
import java.net.MalformedURLException;
import java.net.URL;
import java.net.URLEncoder;
import java.util.ArrayList;
import java.util.HashMap;


import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.client.ClientProtocolException;
import org.apache.http.client.HttpClient;
import org.apache.http.client.entity.UrlEncodedFormEntity;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.message.BasicNameValuePair;
import org.apache.http.util.EntityUtils;


import android.app.Activity;
import android.app.DownloadManager.Request;
import android.os.AsyncTask;
import android.os.Bundle;
import android.os.Environment;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.TextView;


import com.scxh.android1503.R;
import com.scxh.android1503.ui.http.HttpConnectionUtil.HttpCallBack;
import com.scxh.handler.Logs;


public class HttpConnectActivity extends Activity implements OnClickListener {
private Button mConnectBtn, mGetConnetBtn, mPostConnetBtn;
private Button mApachHttpClient, mApachHttpClientGet, mApachHttpClientPost;
private Button mApachHttp,mOkHttpClient;
private TextView mShowMessageTxt;


@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.http_connect_layout);


mConnectBtn = (Button) findViewById(R.id.http_connect_btn);
mShowMessageTxt = (TextView) findViewById(R.id.http_show_message_txt);
mGetConnetBtn = (Button) findViewById(R.id.http_connect_get_btn);
mPostConnetBtn = (Button) findViewById(R.id.http_connect_post_btn);
mApachHttpClient = (Button) findViewById(R.id.http_apache_client_btn);
mApachHttpClientGet = (Button) findViewById(R.id.http_apache_client_get_btn);
mApachHttpClientPost = (Button) findViewById(R.id.http_apache_client_post_btn);
mApachHttp = (Button) findViewById(R.id.http_apache_client_fengzhuang_btn);
mOkHttpClient = (Button) findViewById(R.id.http_okhttp_btn);


mConnectBtn.setOnClickListener(this);
mGetConnetBtn.setOnClickListener(this);
mPostConnetBtn.setOnClickListener(this);
mApachHttpClient.setOnClickListener(this);
mApachHttpClientGet.setOnClickListener(this);
mApachHttpClientPost.setOnClickListener(this);
mApachHttp.setOnClickListener(this);
mOkHttpClient.setOnClickListener(this);
}


@Override
public void onClick(View v) {
switch (v.getId()) {
/* 连接服务器 */
case R.id.http_connect_btn:
String httpUrl = "http://192.168.1.156/app/print";


new AsyncTask<String, Void, String>() {
@Override
protected String doInBackground(String... params) {
String httpUrl = params[0];
try {
URL url = new URL(httpUrl);
HttpURLConnection connect = (HttpURLConnection) url
.openConnection();
connect.setRequestMethod("GET");// 在服务器那边有doGet()方法接受参数
connect.connect();


String str = "";
int statusCode = connect.getResponseCode();
Logs.v("statusCode  :" + statusCode);
if (statusCode == 200) {
str = readStr(connect.getInputStream());
}
return str;


} catch (MalformedURLException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
return null;


}


protected void onPostExecute(String result) {
mShowMessageTxt.setText(result);
}
}.execute(httpUrl);


break;


/* GET传参 */
case R.id.http_connect_get_btn:
httpUrl = "http://192.168.1.156/app/login"; // //http://192.168.1.156/app/login?user=xiaoming&psw=abcd"


String userName = "张三";
try {
userName = URLEncoder.encode(userName, "UTF-8");// 解决传参过程中的乱码问题
} catch (UnsupportedEncodingException e1) {
e1.printStackTrace();
}
httpUrl = httpUrl + "?user=" + userName + "&psw=abcd&sex=男";// "?user="+userName+"&psw=abcd&sex=男"
// GET传参需在httpUrl加传人的内容
Logs.v("httpUrl :" + httpUrl);


new AsyncTask<String, Void, String>() {
@Override
protected String doInBackground(String... params) {
String httpUrl = params[0];
try {
URL url = new URL(httpUrl);
HttpURLConnection connect = (HttpURLConnection) url
.openConnection();
connect.setRequestMethod("GET");
connect.connect();


String str = readStr(connect.getInputStream());
return str;


} catch (MalformedURLException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
return null;


}


protected void onPostExecute(String result) {
mShowMessageTxt.setText(result);
}
}.execute(httpUrl);


break;
case R.id.http_connect_post_btn:
httpUrl = "http://192.168.1.156/app/login";


new AsyncTask<String, Void, String>() {
@Override
protected String doInBackground(String... params) {
Logs.v("doInBackground >>>>>");
String httpUrl = params[0];
try {
URL url = new URL(httpUrl);
HttpURLConnection connect = (HttpURLConnection) url
.openConnection();
connect.setRequestMethod("POST");
connect.connect();


OutputStream os = connect.getOutputStream();
PrintWriter writer = new PrintWriter(os);
writer.print("user=张三&psw=123456");
writer.flush();


String str = readStr(connect.getInputStream());


connect.disconnect();
return str;


} catch (MalformedURLException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
return null;


}


protected void onPostExecute(String result) {
mShowMessageTxt.setText(result);
}
}.execute(httpUrl);
break;
case R.id.http_apache_client_btn:
httpUrl = "http://192.168.1.156/app/print";
new AsyncTask<String, Void, String>() {


@Override
protected String doInBackground(String... params) {
String url = params[0];
HttpClient client = new DefaultHttpClient();
// HttpGet request = new HttpGet(url);
HttpPost request = new HttpPost(url);


try {
HttpResponse response = client.execute(request);
// InputStream is = response.getEntity().getContent();


// String str = readStr(is);
String str = EntityUtils.toString(response.getEntity());
return str;
} catch (ClientProtocolException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
return null;


}


protected void onPostExecute(String result) {
mShowMessageTxt.setText(result);
}


}.execute(httpUrl);


break;


case R.id.http_apache_client_get_btn:


httpUrl = "http://192.168.1.156/app/login";
String parameter = "?user=admin&psw=123456";


httpUrl = httpUrl + parameter;


// String userName1 = "admin";
// try {
// userName1 = URLEncoder.encode(userName1, "UTF-8");// 解决传参过程中的乱码问题
// } catch (UnsupportedEncodingException e1) {
// e1.printStackTrace();
// }
// httpUrl = httpUrl + "?user=" + userName1 + "&psw=123456&sex=男";


new AsyncTask<String, Void, String>() {


@Override
protected String doInBackground(String... params) {
String url = params[0];
HttpClient client = new DefaultHttpClient();
HttpGet request = new HttpGet(url);


try {
HttpResponse response = client.execute(request);
// InputStream is = response.getEntity().getContent();


// String str = readStr(is);
String str = EntityUtils.toString(response.getEntity());
return str;
} catch (ClientProtocolException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
return null;


}


protected void onPostExecute(String result) {
mShowMessageTxt.setText(result);
}


}.execute(httpUrl);


break;


case R.id.http_apache_client_post_btn:
httpUrl = "http://192.168.1.156/app/login";


new AsyncTask<String, Void, String>() {


@Override
protected String doInBackground(String... params) {
String url = params[0];
HttpClient client = new DefaultHttpClient();
HttpPost request = new HttpPost(url);


try {
/* POST传参 */
BasicNameValuePair userNameValue = new BasicNameValuePair(
"user", "张三");
BasicNameValuePair pswNameValue = new BasicNameValuePair(
"psw", "123456");
ArrayList<BasicNameValuePair> pairs = new ArrayList<BasicNameValuePair>();
pairs.add(userNameValue);
pairs.add(pswNameValue);


HttpEntity entity = new UrlEncodedFormEntity(pairs,
"UTF-8");
request.setHeader("content-Type",
"application/x-www-form-urlencoded;charset=utf-8");
request.setEntity(entity);


HttpResponse response = client.execute(request);
// InputStream is = response.getEntity().getContent();
// String str = readStr(is);
String str = EntityUtils.toString(response.getEntity());
return str;
} catch (ClientProtocolException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
return null;


}


protected void onPostExecute(String result) {
mShowMessageTxt.setText(result);
}


}.execute(httpUrl);


break;


case R.id.http_apache_client_fengzhuang_btn:
String url = "http://192.168.1.156/app/login";
HashMap<String, Object> map = new HashMap();
map.put("user", "王二1");
map.put("psw", "abcd");


/*
通常的使用场景之一:
当函数参数是接口类型时,而且接口中的方法不超过三个。
可以用匿名内部类作为实际参数进行传递
*/

new HttpConnectionUtil().asyncTaskHttps(url,
HttpConnectionUtil.Method.POST, map, new HttpCallBack() {//匿名内部类:其实就是一个匿名子类对象。 
@Override
public void returnMessage(String message) {
mShowMessageTxt.setText(message);
}
});


/*String url = "http://192.168.1.156/app/print";//无参传递
* new HttpConnectionUtil().asyncTaskHttp(url, Method.POST, new HttpCallBack() {

@Override
public void returnMessage(String message) {
if(message != null){
mShowMessageTxt.setText(message);
}
}
});*/


break;

/**
* 从输入流读数据

* @param is
* @return
* @throws IOException
*/
public String readStr(InputStream is) throws IOException {
BufferedReader reader = new BufferedReader(new InputStreamReader(is,
"UTF-8"));
StringBuilder sb = new StringBuilder();
String line;
while ((line = reader.readLine()) != null) {
sb.append(line);
}
reader.close();
is.close();
return sb.toString();
}


public String getHttpConnect(String httpUrl) {
try {
/** Get请求传参方式 */
httpUrl = httpUrl + "?user=admin&psw=abcd"; // http://192.168.1.156/app/login?user=xiaoming&psw=abcd"
URL url = new URL(httpUrl); // 统一资源定位符
HttpURLConnection connet = (HttpURLConnection) url.openConnection(); // 打开Http连接
connet.setRequestMethod("GET"); // 设置 http请求方式
connet.setConnectTimeout(15000); // 设置http连接超时时间
connet.setReadTimeout(10000); // 设置读数据超时时间
connet.connect(); // 建立连接


/**
* post传参实现方式 : 向字节输出流中写数据
*/
/*
* OutputStream os = connet.getOutputStream(); PrintWriter pw = new
* PrintWriter(os); pw.print("user=xiaoming&psw=abcd"); pw.flush();
*/


InputStream is = connet.getInputStream(); // 得到字节输入流
BufferedReader reader = new BufferedReader(new InputStreamReader(
is, "UTF-8")); // 得到字符输入缓冲流


/**
* 从字符输入缓冲流中一行一行读取数据 添加到StringBuilder
*/
String line;
StringBuilder sb = new StringBuilder();
while ((line = reader.readLine()) != null) {
sb.append(line);
}


return sb.toString();


} catch (MalformedURLException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
return null;
}

}



定义了一个工具类,在进行Http连接时 可调用工具类直接使用:

package com.scxh.android1503.ui.http;


import java.io.IOException;
import java.io.UnsupportedEncodingException;
import java.net.HttpURLConnection;
import java.util.ArrayList;
import java.util.HashMap;


import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.client.ClientProtocolException;
import org.apache.http.client.HttpClient;
import org.apache.http.client.entity.UrlEncodedFormEntity;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.client.methods.HttpUriRequest;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.message.BasicNameValuePair;
import org.apache.http.protocol.HTTP;
import org.apache.http.util.EntityUtils;


import com.scxh.pattern.callback.CallInterfacel;


import android.R.integer;
import android.os.AsyncTask;


public class HttpConnectionUtil {
public enum Method {
GET,POST
}


/** 第一步定义接口 */
public interface HttpCallBack {
public void returnMessage(String message);
}


/** 注册接口 */
public HttpCallBack mHttpCallBack;


/**
* 无参处理

* @param url
* @param method
* @param httpCallBack
*/
public void asyncTaskHttp(String url, final Method method,
HttpCallBack httpCallBack) {
asyncTaskHttps(url, method, null, httpCallBack);
}


/**
* 有参处理

* 根据传URI 参数,请求方式, 从服务端获取数据

* @param url
* @param method
* @param parameter
* @return
*/
public void asyncTaskHttps(final String url, final Method method,
final HashMap<String, Object> parameter, HttpCallBack httpCallBack) {
mHttpCallBack = httpCallBack;
new AsyncTask<String, Void, String>() {


@Override
protected String doInBackground(String... params) {
return getDataByHttpClient(url, method, parameter);
}


@Override
protected void onPostExecute(String result) {
super.onPostExecute(result);
mHttpCallBack.returnMessage(result);
}
}.execute(url);


}


/**
* 网络获取数据

* @param url
* @param method
* @param parameter
* @return
*/
public String getDataByHttpClient(String url, final Method method,
final HashMap<String, Object> parameter) {
String str = null;
try {
//实现化HttpClient获取客服端http连接
HttpClient httpClient = new DefaultHttpClient();
//实始化Http请求,获取请求与服务端的连接(HttpUriRequest request = new HttpGet(url))
HttpUriRequest request = getHttpRequest(url, method, parameter); 
//执行Http请求得到响应实例
HttpResponse response = httpClient.execute(request);  //执行Http请求得到响应实例
//如果得到响应的状态码为200则表示获取成功(连接成功)
if(response.getStatusLine().getStatusCode() == HttpURLConnection.HTTP_OK){
str = EntityUtils.toString(response.getEntity());  
}else{
str = "网络出错";
}

} catch (ClientProtocolException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}

return str;


}


/**
* Http请求处理
* @param url
* @param method
* @param parameter
* @return
*/
public HttpUriRequest getHttpRequest(String url, final Method method,
final HashMap<String, Object> parameter) {
if (method.equals(Method.GET)) {
if (parameter != null) {
/**
* 组装Get请求参数 http://192.168.1.156/app/login?user=张三&psw=123456"
* */
url = url + "?";
//字符串累加
StringBuilder sb = new StringBuilder(url);
for (String key : parameter.keySet()) {
//通过键获取集合中的值
Object values = parameter.get(key);
sb.append(key);
sb.append("=");
sb.append(values);
sb.append("&");
}
url = sb.substring(0, sb.length() - 1);//累加最后会多一个&符号,所以调用substring()方法减去
}


return new HttpGet(url);
} else {
HttpPost request = new HttpPost(url);
if (parameter != null) {
/** post传参 */
ArrayList<BasicNameValuePair> pairs = new ArrayList<BasicNameValuePair>();
for (String key : parameter.keySet()) {
Object values = parameter.get(key);
BasicNameValuePair userNameValue = new BasicNameValuePair(
key, (String) values);
pairs.add(userNameValue);
}
try {
HttpEntity entity = new UrlEncodedFormEntity(pairs,
HTTP.UTF_8);
request.setEntity(entity);
} catch (UnsupportedEncodingException e) {
e.printStackTrace();
}


}


return request;
}
}


}


在服务端的demo:

package www.scxh.web1503;


import java.io.IOException;
import java.io.PrintWriter;


import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;


public class LoginServlet extends HttpServlet {
@Override
protected void doGet(HttpServletRequest req, HttpServletResponse resp)
throws ServletException, IOException {
resp.setContentType("text/html;charset=utf-8"); // 解决响应请求中文乱码


String userName = req.getParameter("user");
String passWord = req.getParameter("psw");
System.out.println("doGet userName :"+userName+ " passWord :"+passWord);

/**乱码解决方法一*/
// String user_Name = new String(userName.getBytes("ISO-8859-1"),"UTF-8");
// System.out.println("doGet user_Name :"+user_Name+ " passWord :"+passWord);



PrintWriter writer = resp.getWriter();

if(userName.equals("admin")){
writer.print("<html><body><h1>"+userName+"登录成功 </h1></body></html>");
}else{
writer.print("<html><body><h1>"+userName+"登录失败 </h1></body></html>");
}
}
}



package www.scxh.web1503;


import java.io.IOException;
import java.io.PrintWriter;


import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;


public class PrintServlet extends HttpServlet {
@Override
protected void doGet(HttpServletRequest req, HttpServletResponse resp)
throws ServletException, IOException {


resp.setContentType("text/html;charset=utf-8");


// 当接受客服端发来的消息时 回传下面的内容


PrintWriter writer = resp.getWriter();
writer.write("GET  请求成功!");


}


@Override
protected void doPost(HttpServletRequest req, HttpServletResponse resp)
throws ServletException, IOException {
resp.setContentType("text/html;charset=utf-8");


// 当接受客服端发来的消息时 回传下面的内容


PrintWriter writer = resp.getWriter();
writer.write("POST  请求成功!");


}


}



在服务端的WebRoot下面的WEB-INF下注册客服端请求时响应的类:

<?xml version="1.0" encoding="UTF-8"?>


<web-app version = "2.5" xmlns="http://xmlns.jcp.org/xml/ns/javaee"
>


    




    <servlet>
      <servlet-name>LoginServlet</servlet-name>
      <servlet-class>www.scxh.web1503.LoginServlet</servlet-class>
    </servlet>
    
    
    <servlet>
      <servlet-name>PrintServlet</servlet-name>
      <servlet-class>www.scxh.web1503.PrintServlet</servlet-class>
    </servlet>
  


    <servlet-mapping>
        <servlet-name>LoginServlet</servlet-name>
        <url-pattern>/login</url-pattern>
    </servlet-mapping>
    
     <servlet-mapping>
        <servlet-name>PrintServlet</servlet-name>
        <url-pattern>/print</url-pattern>
    </servlet-mapping>
 


</web-app>


0
0

查看评论
* 以上用户言论只代表其个人观点,不代表CSDN网站的观点或立场
    个人资料
    • 访问:22573次
    • 积分:571
    • 等级:
    • 排名:千里之外
    • 原创:28篇
    • 转载:52篇
    • 译文:0篇
    • 评论:0条