android:HttpClient请求(get、post)

来源:互联网 发布:php 图片上传的原理 编辑:程序博客网 时间:2024/05/29 14:16

本文主要介绍android如何通过HttpClient请求服务器端的内容

一:服务器端代码准备

     web.xml配置文件
    
<?xml version="1.0" encoding="ISO-8859-1"?><!--  Licensed to the Apache Software Foundation (ASF) under one or more  contributor license agreements.  See the NOTICE file distributed with  this work for additional information regarding copyright ownership.  The ASF licenses this file to You under the Apache License, Version 2.0  (the "License"); you may not use this file except in compliance with  the License.  You may obtain a copy of the License at      http://www.apache.org/licenses/LICENSE-2.0  Unless required by applicable law or agreed to in writing, software  distributed under the License is distributed on an "AS IS" BASIS,  WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.  See the License for the specific language governing permissions and  limitations under the License.--><web-app xmlns="http://java.sun.com/xml/ns/javaee"  xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"  xsi:schemaLocation="http://java.sun.com/xml/ns/javaee                      http://java.sun.com/xml/ns/javaee/web-app_3_0.xsd"  version="3.0"  metadata-complete="true">    <description>      androidweb    </description>    <display-name>androidweb</display-name>     <servlet>      <servlet-name>login</servlet-name>      <servlet-class>com.smart.androidweb.servlet.LoginServlet</servlet-class>    </servlet>     <servlet-mapping>        <servlet-name>login</servlet-name>        <url-pattern>/login</url-pattern>    </servlet-mapping>    <welcome-file-list>        <welcome-file>index.html</welcome-file>        <welcome-file>index.xhtml</welcome-file>        <welcome-file>index.htm</welcome-file>        <welcome-file>index.jsp</welcome-file>    </welcome-file-list></web-app>

  2.Servlet代码准备LoginServlet.java
package com.smart.androidweb.servlet;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 {/** *  */private static final long serialVersionUID = 1L;@Overrideprotected void doGet(HttpServletRequest req, HttpServletResponse resp)throws ServletException, IOException {// TODO Auto-generated method stub//在网上很有效的解决方法是添加:resp.setCharacterEncoding("UTF-8");//解决不了,后来又搜到一条解决方法是:resp.setHeader("content-type","text/html;charset=UTF-8");String username = req.getParameter("username");String password = req.getParameter("password");PrintWriter writer = resp.getWriter();if("".equals(username) || username == null) {writer.print("用户名不能为空!");return ;}if("".equals(password) || password == null) {writer.print("密码不能为空");return ;}if("testname".equals(username) && "123456".equals(password)) {writer.print("登陆成功");} else {writer.print("登陆失败");}}@Overrideprotected void doPost(HttpServletRequest req, HttpServletResponse resp)throws ServletException, IOException {// TODO Auto-generated method stub//resp.setreqdoGet(req, resp);}}

二:android端代码准备
    1)不要忘记在清单文件中添加网络访问权限
    
<uses-permission android:name="android.permission.INTERNET"></uses-permission>
 2)android开发工具倒入一下两个jar包(没有的可以在网络上搜索下载一下)
httpclient-4.0.1.jar,httpcore-4.0.1.jar
 3)布局文件
activity_main.xml
<?xml version="1.0" encoding="utf-8"?><RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"    xmlns:tools="http://schemas.android.com/tools" android:id="@+id/activity_main"    android:layout_width="match_parent" android:layout_height="match_parent"    android:paddingBottom="@dimen/activity_vertical_margin"    android:paddingLeft="@dimen/activity_horizontal_margin"    android:paddingRight="@dimen/activity_horizontal_margin"    android:paddingTop="@dimen/activity_vertical_margin"    tools:context="com.smart.httpclient.activity.MainActivity">    <LinearLayout        android:orientation="vertical"        android:layout_width="match_parent"        android:layout_height="match_parent">        <LinearLayout                  android:orientation="horizontal"            android:layout_width="match_parent"            android:layout_height="wrap_content">            <TextView                android:text="用户名:"                android:layout_width="wrap_content"                android:layout_height="wrap_content" />            <EditText                android:id="@+id/et_username"                android:text="testname"                android:layout_width="match_parent"                android:layout_height="wrap_content" />        </LinearLayout>        <LinearLayout            android:orientation="horizontal"            android:layout_width="match_parent"            android:layout_height="wrap_content">            <TextView                android:text="密  码:"                android:layout_width="wrap_content"                android:layout_height="wrap_content" />            <EditText                android:id="@+id/et_password"                android:inputType="textPassword"                android:layout_width="match_parent"                android:layout_height="wrap_content" />        </LinearLayout>        <LinearLayout            android:orientation="horizontal"            android:layout_width="match_parent"            android:layout_height="wrap_content">            <Button                android:text="Get请求"                android:id="@+id/bt_submit"                android:onClick="onClick"                android:layout_width="wrap_content"                android:layout_height="wrap_content" />            <Button                android:id="@+id/bt_cannel"                android:text="Post请求"                android:onClick="onClick"                android:layout_width="wrap_content"                android:layout_height="wrap_content" />        </LinearLayout>    </LinearLayout></RelativeLayout>
4)java端代码
MainActivity.java
package com.smart.httpclient.activity;import android.support.v7.app.AppCompatActivity;import android.os.Bundle;import android.view.View;import android.widget.EditText;import android.widget.Toast;import org.apache.http.HttpResponse;import org.apache.http.NameValuePair;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 java.io.IOException;import java.util.ArrayList;import java.util.List;public class MainActivity extends AppCompatActivity {    EditText et_username;    EditText et_password;    @Override    protected void onCreate(Bundle savedInstanceState) {        super.onCreate(savedInstanceState);        setContentView(R.layout.activity_main);        et_username = (EditText)findViewById(R.id.et_username);        et_password = (EditText)findViewById(R.id.et_password);    }    public void onClick(View v) {        if(v.getId() == R.id.bt_cannel) {           loginPost();        } else  if(v.getId() == R.id.bt_submit) {            loginGet();        }    }    /**     * GET方式请求数据     */    public void loginGet() {        new Thread(new Runnable() {            @Override            public void run() {                String username = et_username.getText().toString().trim();                String password = et_password.getText().toString().trim();                //网络请求地址                String urlPath = "http://192.168.1.6:8080/androidweb/login?username="+username+"&password="+password;                //创建客户端请求对象                DefaultHttpClient client = new DefaultHttpClient();                //以GET的方式进行请求                HttpGet get = new HttpGet(urlPath);                try {                    //获取服务器响应对象                    HttpResponse response = client.execute(get);                    //获取请求码200正确,404网址不存在,500服务器程序错误                    int code = response.getStatusLine().getStatusCode();                    if(code == 200) {                       // 功过工具类把response的输出流转换成字符串                        String content = EntityUtils.toString(response.getEntity(),"utf-8");                        //显示获取的内容                        showToast(content);                    }                } catch (IOException e) {                    e.printStackTrace();                }            }        }).start();    }    /**     * Post方式请求数据,为安全起见都用post     */    public void loginPost() {        new Thread(new Runnable() {            @Override            public void run() {                String username = et_username.getText().toString().trim();                String password = et_password.getText().toString().trim();                //网络请求地址                String urlPath = "http://192.168.1.6:8080/androidweb/login";//?username="+username+"&password="+password;                //创建客户端请求对象                DefaultHttpClient client = new DefaultHttpClient();                //以Post的方式进行请求                HttpPost post = new HttpPost(urlPath);                //封装http求取参数                List<NameValuePair> params = new ArrayList<NameValuePair>();                NameValuePair pairun = new BasicNameValuePair("username",username);                NameValuePair pairpw = new BasicNameValuePair("password",password);                params.add(pairun);                params.add(pairpw);                try {                    //组装请求内容                    UrlEncodedFormEntity entity = new UrlEncodedFormEntity(params);                    //设置请求参数                    post.setEntity(entity);                    //获取服务器响应对象                    HttpResponse response = client.execute(post);                    //获取请求码200正确,404网址不存在,500服务器程序错误                    int code = response.getStatusLine().getStatusCode();                    if(code == 200) {                        // 功过工具类把response的输出流转换成字符串                        String content = EntityUtils.toString(response.getEntity(),"utf-8");                        //显示获取的内容                        showToast(content);                    }                } catch (Exception e) {                    e.printStackTrace();                }            }        }).start();    }    /**     * 封装吐司方法,使其在任意位置都可显示。     * @param content     */    public void showToast(final String content) {        runOnUiThread(new Runnable() {            @Override            public void run() {                Toast.makeText(getApplicationContext(),content,Toast.LENGTH_LONG).show();            }        });    }}


0 0