使用HttpURLConnection和使用HttpClient方式请求网络采用get方式和post方式请求数据
来源:互联网 发布:日历js脚本 编辑:程序博客网 时间:2024/05/16 14:45
学习知识:
1.android终端通过POST/GET请求到服务器返回请求
2.涉及到POST请求和GET请求
3.GET请求方式乱码问题
在Activity中:这个地方通过调用Get和Post方法
public class MainActivity extends Activity {private EditText etUserName;private EditText etPassword;@Overrideprotected void onCreate(Bundle savedInstanceState) {super.onCreate(savedInstanceState);setContentView(R.layout.activity_main);etUserName=(EditText)findViewById(R.id.et_username);etPassword=(EditText)findViewById(R.id.et_password);}public void doGet(View v) {final String userName = etUserName.getText().toString();final String password = etPassword.getText().toString();new Thread(new Runnable() {@Overridepublic void run() {// <strong>使用get方式抓去数据</strong>final String state = <strong><span style="color:#ff0000;">NetUtils.loginOfGet(userName, password);</span>// 执行任务在主线程中,ruOnUiThread相当于Handler信息共享的作用runOnUiThread(new Runnable() {@Overridepublic void run() {// 就是在主线程中操作,Toast.makeText(MainActivity.this, state, 0).show();}});</strong>}}).start();}public void doPost(View v){final String userName=etUserName.getText().toString();final String password=etPassword.getText().toString();new Thread(new Runnable(){@Overridepublic void run() {final String state=<span style="color:#cc0000;"><strong>NetUtils.loginOfPost(userName, password);</strong></span>//执行线程在主线程中runOnUiThread(new Runnable(){@Overridepublic void run() {//就是在主线程中操作Toast.makeText(MainActivity.this,state,0).show();}});}}).start();} }
在NetUtils中看看loginOfGet和loginOfPost方法中
分析:你会发现get和post的请求方式都差不多,下面分析一下区别和请求服务器程序的思路。
思路:
1.请求URL请求:URL url=new URL(http://10.0.2.2:8081/ServerItheima28/servlet/LoginServlet);
2.通过url来得到HttpURLConnection连接:conn=(HttpURLConnection) url.openConnection();
3.通过连接conn设置相关参数:setRequestMethod setConnectTimeout setReadTimeout setDoOutput(true); //必须设置此方法,允许输出
4.通过连接conn来得到服务器的响应码:responseCode=conn.getResponseCode();
5.通过响应码来判断,然后通过连接得到输入流【为了让服务器上的数据】:InputStream is=conn.getInputStream();
6.将流转换成String类型字符串:这就是我们需要得到的数据,如果说是图片就要将流转换成字符串、bitmap对象。String state=getStringFromInputStream(is);
在本例子中:getStringFromInputStream(InputStream is)非常重要
GET/POST区别:
这个地方主要是参数传递区别:
Post请求的时候:
URL url=new URL("http://10.0.2.2:8081/ServerItheima28/servlet/LoginServlet");
OutputStream out=conn.getOutputStream();
out.write(data.getBytes());
Get请求的时候:
String data = "username=" + URLEncoder.encode(userName) + "&password=" + URLEncoder.encode(password);
URL url = new URL("http://10.0.2.2:8081/ServerItheima28/servlet/LoginServlet?" + data);
区别就在这里:向服务器传递参数的时候,
POST请求的时候是在程序中将参数通过流的方式传递到服务器
GET请求的时候,是在url中将参数传递到服务器
public class NetUtils {private static final String TAG="NetUtils";/* * 使用Post登陆方式 * */public static String <strong>loginOfPost</strong>(String userName,String password){HttpURLConnection conn=null;try {<strong>URL url=new URL("http://10.0.2.2:8081/ServerItheima28/servlet/LoginServlet");conn=(HttpURLConnection) url.openConnection();</strong>conn.setRequestMethod("POST");conn.setConnectTimeout(10000); conn.setReadTimeout(5000);<strong>conn.setDoOutput(true); //必须设置此方法,允许输出</strong>//post请求参数<strong>String data="username="+userName+"&password="+password;</strong>//获得一个输出流,用于向服务器写数据,默认情况下,系统是不允许向服务器输出数据OutputStream out=conn.getOutputStream();<strong>out.write(data.getBytes());</strong>out.flush();out.close();int responseCode=conn.getResponseCode();if(responseCode==200){InputStream is=conn.getInputStream();String state=getStringFromInputStream(is);<strong>return state;</strong>}else{Log.i(TAG,"访问失败:"+responseCode);}} catch (Exception e) {// TODO Auto-generated catch blocke.printStackTrace();}finally{if(conn!=null){conn.disconnect(); //关闭连接}}return null;}/* * 根据流返回一个字符串信息 */<strong>private static String getStringFromInputStream(InputStream is) throws IOException {ByteArrayOutputStream baos=new ByteArrayOutputStream();byte[] buffer=new byte[1024];int len=-1;while((len=is.read(buffer))!=-1){baos.write(buffer,0,len);}is.close();//把流中的数据转换成字符串,采用的事utf-8编码String html=baos.toString();baos.close(); return html;}</strong>/* * 使用get方式登录 */public static String loginOfGet(String userName, String password) {HttpURLConnection conn = null;try {String data = "username=" + URLEncoder.encode(userName) + "&password=" + URLEncoder.encode(password);URL url = new URL("http://10.0.2.2:8081/ServerItheima28/servlet/LoginServlet?" + data);conn = (HttpURLConnection) url.openConnection();conn.setRequestMethod("GET");// get或者post必须得全大写conn.setConnectTimeout(10000); // 连接的超时时间conn.setReadTimeout(5000); // 读数据的超时时间conn.setDoOutput(true); int responseCode = conn.getResponseCode();if(responseCode == 200) {InputStream is = conn.getInputStream();String state = getStringFromInputStream(is);return state;} else {Log.i(TAG, "访问失败: " + responseCode);}} catch (Exception e) {e.printStackTrace();} finally {if(conn != null) {conn.disconnect();// 关闭连接}}return null;}}
在服务器端的代码:这个地方需要掌握的就是编码问题
public class LoginServlet extends HttpServlet {public void doGet(HttpServletRequest request, HttpServletResponse response)throws ServletException, IOException {String username = request.getParameter("username");// 采用的编码是: iso-8859-1String password = request.getParameter("password");<strong>// 采用iso8859-1的编码对姓名进行逆转, 转换成字节数组, 再使用utf-8编码对数据进行转换, 字符串</strong>
<strong> //特别是GET发送请求的时候,在浏览器传递参数过程中,浏览器默认的事ISO8859-1的编码username = new String(username.getBytes("iso8859-1"), "utf-8");password = new String(password.getBytes("iso8859-1"), "utf-8");</strong>
if("lisi".equals(username) && "123".equals(password)) {/* * <strong>getBytes 默认情况下, 使用的iso8859-1的编码, 但如果发现码表中没有当前字符,</strong> * 会使用当前系统下的默认编码: GBK */ response.getOutputStream().write("登录成功".getBytes("utf-8"));} else {response.getOutputStream().write("登录失败".getBytes("utf-8"));}}public void doPost(HttpServletRequest request, HttpServletResponse response)throws ServletException, IOException {System.out.println("doPost");doGet(request, response);}}
下面介绍一下:github上Android非常火的请求插件:android-async-http-master
public class MainActivity2 extends Activity {protected static final String TAG = "MainActivity2";private EditText etUserName;private EditText etPassword;@Overrideprotected void onCreate(Bundle savedInstanceState) {super.onCreate(savedInstanceState);setContentView(R.layout.activity_main);etUserName = (EditText) findViewById(R.id.et_username);etPassword = (EditText) findViewById(R.id.et_password);}public void doGet(View v) {final String userName = etUserName.getText().toString();final String password = etPassword.getText().toString(); AsyncHttpClient client = new AsyncHttpClient(); String data = "username=" + URLEncoder.encode(userName) + "&password=" + URLEncoder.encode(password); client.get("http://10.0.2.2:8080/ServerItheima28/servlet/LoginServlet?" + data, new MyResponseHandler());}public void doPost(View v) {final String userName = etUserName.getText().toString();final String password = etPassword.getText().toString();AsyncHttpClient client = new AsyncHttpClient(); RequestParams params = new RequestParams(); params.put("username", userName); params.put("password", password); client.post("http://10.0.2.2:8080/ServerItheima28/servlet/LoginServlet", params, new MyResponseHandler());}class MyResponseHandler extends AsyncHttpResponseHandler {@Overridepublic void onSuccess(int statusCode, Header[] headers,byte[] responseBody) {//Log.i(TAG, "statusCode: " + statusCode);Toast.makeText(MainActivity2.this, "成功: statusCode: " + statusCode + ", body: " + new String(responseBody), 0).show();}@Overridepublic void onFailure(int statusCode, Header[] headers,byte[] responseBody, Throwable error) {Toast.makeText(MainActivity2.this, "失败: statusCode: " + statusCode, 0).show();} }}
只需要用仅仅几行代码实现所有功能。
项目代码下载地址,可参考:http://download.csdn.net/detail/itjavawfc/8136795
第二种请求参数:下面介绍HttpClient来实现请求
NetUtils2.java
public class NetUtils2 {private static final String TAG="NetUtils";/* * 使用Post登陆方式 * */ public static String loginOfPost(String userName,String password){HttpClient client = null;try {// 定义一个客户端client = new DefaultHttpClient();// 定义post方法HttpPost post = new HttpPost("http://10.0.2.2:8081/ServerItheima28/servlet/LoginServlet");// 定义post请求的参数List<NameValuePair> parameters = new ArrayList<NameValuePair>();parameters.add(new BasicNameValuePair("username", userName));parameters.add(new BasicNameValuePair("password", password));// 把post请求的参数包装了一层.// 不写编码名称服务器收数据时乱码. 需要指定字符集为utf-8UrlEncodedFormEntity entity = new UrlEncodedFormEntity(parameters, "utf-8");// 设置参数.post.setEntity(entity);// 设置请求头消息//post.addHeader("Content-Length", "20");// 使用客户端执行post方法HttpResponse response = client.execute(post);// 开始执行post请求, 会返回给我们一个HttpResponse对象// 使用响应对象, 获得状态码, 处理内容int statusCode = response.getStatusLine().getStatusCode();// 获得状态码if(statusCode == 200) {// 使用响应对象获得实体, 获得输入流InputStream is = response.getEntity().getContent();String text = getStringFromInputStream(is);return text;} else {Log.i(TAG, "请求失败: " + statusCode);}} catch (Exception e) {e.printStackTrace();} finally {if(client != null) {client.getConnectionManager().shutdown();// 关闭连接和释放资源}}return null;} /* * 使用get方式的登陆 */ public static String loginOfGet(String userName,String password){ HttpClient client=null; try { //定义一个客户端 client=new DefaultHttpClient(); //定义了一个get请求方法 String data="username="+userName+"&password="+password; HttpGet get=new HttpGet("http://10.0.2.2:8081/ServerItheima28/servlet/LoginServlet?" + data); //response服务器相应对象,其中包含了状态信息和服务器返回的数据HttpResponse response=client.execute(get); // 开始执行get方法, 请求网络//获得响应码int statusCode=response.getStatusLine().getStatusCode();if(statusCode==200){ InputStream is=response.getEntity().getContent(); String text=getStringFromInputStream(is); return text;}else{Log.i(TAG,"请求失败:"+statusCode);} }catch (Exception e) {// TODO Auto-generated catch blocke.printStackTrace();}finally{if(client!=null){client.getConnectionManager().shutdown();}} return null; } private static String getStringFromInputStream(InputStream is) throws IOException {ByteArrayOutputStream baos=new ByteArrayOutputStream();byte[] buffer=new byte[1024];int len=-1;while((len=is.read(buffer))!=-1){baos.write(buffer,0,len);}is.close();// 把流中的数据转换成字符串, 采用的编码是: utf-8String html=baos.toString();// 把流中的数据转换成字符串, 采用的编码是: utf-8baos.close();return html;}}
使用HttpClient方式发送Get请求:要点
HttpClient client = null;try {client = new DefaultHttpClient();// 定义一个客户端String data = "username=" + userName + "&password=" + password;// 定义一个get请求HttpGet get = new HttpGet("http://10.0.2.2:8080/Server/servlet/LoginServlet?" + data);HttpResponse response = client.execute(get);// 开始执行请求int statusCode = response.getStatusLine().getStatusCode();// 获得响应码if(statusCode == 200) {// 响应码等于200, 请求成功// 请求成功, 进行相关处理.}} catch (Exception e) {e.printStackTrace();} finally {if(client != null) {client.getConnectionManager().shutdown();// 断开连接.}}
HttpClient client = null;try {client = new DefaultHttpClient(); // 定义客户端// 定义post请求HttpPost post = new HttpPost("http://10.0.2.2:8080/Server/servlet/LoginServlet");// 定义请求参数List<BasicNameValuePair> parameters = new ArrayList<BasicNameValuePair>();parameters.add(new BasicNameValuePair("username", userName));parameters.add(new BasicNameValuePair("password", password));post.setEntity(new UrlEncodedFormEntity(parameters));// 把参数添加到Post请求中HttpResponse response = client.execute(post); // 执行访问int statusCode = response.getStatusLine().getStatusCode();// 获得响应码if(statusCode == 200) {// 响应码等于200, 请求成功// 请求成功, 处理相关业务.}} catch (Exception e) {e.printStackTrace();} finally {if(client != null) {client.getConnectionManager().shutdown();}}
- 使用HttpURLConnection和使用HttpClient方式请求网络采用get方式和post方式请求数据
- 使用HttpURLConnection采用get方式或post方式请求数据
- 使用HttpURLConnection采用Post方式请求数据
- 使用HttpURLConnection采用Post方式请求数据
- 使用HttpURLConnection采用get方式请求数据-----乱码问题
- HttpURLConnection的GET和POST请求方式
- Android使用HttpClient以Post、Get请求服务器发送数据的方式(普通和json)
- Android使用HttpClient以Post、Get请求服务器发送数据的方式(普通和json)
- Android使用HttpClient以Post、Get请求服务器发送数据的方式(普通和json)
- HttpUrlConnection以GET方式和POST方式请求服务器
- httpURLConnection-网络请求的两种方式-get请求和post请求
- httpURLConnection-网络请求的两种方式-get请求和post请求
- HttpUrlConnection和HttpClient两种方式获取GET和POST请求
- java网络请求GET和POST方式
- get 和post 方式请求数据
- HttpURLConnection GET 方式 请求网络数据
- 安卓网络请求使用httpclient--post请求方式
- android 使用HttpURLConnection方式提交get/post请求
- hdu 2795(Billboard) 广告牌
- Oracle逻辑体系
- Sicily 1147. 谁拿了最多奖学金
- 常用系统的下载链接
- 关于dsp中的bootmode资料
- 使用HttpURLConnection和使用HttpClient方式请求网络采用get方式和post方式请求数据
- uva 348 Optimal Array Multiplication Sequence
- (三)线程同步工具集_2---控制并发访问资源的多个副本
- 实现push pop min皆为O(1)的栈
- 成员模板2
- 更改servlet插件自动生成的内容
- 【Leetcode】Roman to Integer JAVA
- servlet生命周期
- MAC下解决访问本地JSP页面500和404问题