设为首页 收藏本站
查看: 1240|回复: 0

[经验分享] Android 网络应用

[复制链接]

尚未签到

发表于 2018-11-21 11:53:53 | 显示全部楼层 |阅读模式
  使用HttpClient发送请求,接收响应很简单,只要5步:

  •   创建HttpClient 对象
  •   创建HttpGet对象;或者是HttpPost 对象
  •   如果需要发送请求参数,可以调用HttpGet HttpPost共同的setParams(HttpParams params) 方法来添加请求参数;对于HttpPost对象,也可以调用setEntity(HttpEntity entity)方法来设置请求参数
      

      

客户端条件参数:
List params = new
                                                    ArrayList();
                                            params.add(new BasicNameValuePair
                                                    ("LoginName", name));
                                            params.add(new BasicNameValuePair
                                                    ("LoginPassword", pass));
                                            // 设置编码
                                            post.setEntity(new UrlEncodedFormEntity(
                                                    params, HTTP.UTF_8));服务器端接收:
String loginName = request.getParameter("LoginName");
String loginPassword = request.getParameter("LoginPassword");  4.调用HttpClient对象的excute()发送请求,返回一个HttpResponse 对象。
  5.调用HttpResponse的getAllHeaders(),getHeaders()等方法可以获取服务器的响应头;调用HttpResponse的getEntity()可以获取HttpEntity对象,该对象包转了服务器的响应内容。
  

  登录的实例:核心代码
  服务器端用的servlet搭建
package LoginServlet;
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 AndroidLoginServler extends HttpServlet {
private static final long serialVersionUID = 1L;
public AndroidLoginServler() {
super();
}
public void doGet(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
this.doPost(request, response);
System.out.println("doGet");
}
// Url 地址
// http://localhost:8080/Android_Client/servlet/AndroidLoginServler?LoginName=yu&LoginPassword=123
public void doPost(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
System.out.println("doPost");
request.setCharacterEncoding("UTF-8");
String loginName = request.getParameter("LoginName");
String loginPassword = request.getParameter("LoginPassword");
System.out.println(loginName);
System.out.println(loginPassword);
// 统一字符 避免乱码
response.setCharacterEncoding("UTF-8");
response.setContentType("text/html;charset=UTF-8");
PrintWriter out = null;
try {
/*
* 登录业务判断
*/
out=response.getWriter();
if (loginName.equals("yu") && loginPassword.equals("123")) {
// 登陆成功
out.print("success");
} else {
// 登陆失败
out.print("failed");
}
} finally {
if (out != null)
out.close();
}
}
}  客户端

package com.example.xiaocool.httpclienttest;
import android.app.AlertDialog;
import android.content.DialogInterface;
import android.os.Bundle;
import android.os.Handler;
import android.os.Looper;
import android.os.Message;
import android.support.v7.app.ActionBarActivity;
import android.view.View;
import android.widget.EditText;
import android.widget.TextView;
import android.widget.Toast;
import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.NameValuePair;
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.protocol.HTTP;
import org.apache.http.util.EntityUtils;
import java.io.BufferedReader;
import java.io.InputStreamReader;
import java.util.ArrayList;
import java.util.List;

public class MainActivity extends ActionBarActivity {
    TextView response;
    HttpClient httpClient;
    Handler handler = new Handler() {
        public void handleMessage(Message msg) {
            if (msg.what == 0x123) {
                response.append(msg.obj.toString() + "\n");
            }
        }
    };
    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.main);
        // 创建DefaultHttpClient对象
        httpClient = new DefaultHttpClient();
        response = (TextView) findViewById(R.id.response);
    }
    public void accessSecret(View v) {
        response.setText("");
        new Thread() {
            @Override
            public void run() {
                // 创建HttpGet对象
                HttpGet get = new HttpGet(
                        "http://112.237.241.204:8080/Android_Client/servlet/AndroidLoginServler?LoginName=yu&LoginPassword=123");
                try {
                    // 发送get
                    HttpResponse httpResponse = httpClient.execute(get);
                    HttpEntity entity = httpResponse.getEntity();
                    if (entity != null) {
                        BufferedReader br = new BufferedReader(
                                new InputStreamReader(entity.getContent()));
                        String line = null;
                        while ((line = br.readLine()) != null) {
                            Message msg = new Message();
                            msg.what = 0x123;
                            msg.obj = line;
                            handler.sendMessage(msg);
                        }
                    }
                } catch (Exception e) {
                    e.printStackTrace();
                }
            }
        }.start();
    }
    public void showLogin(View v) {
        //加载登陆界面
        final View loginDialog = getLayoutInflater().inflate(
                R.layout.login, null);
        //使用对话框供用户登陆系统
       new AlertDialog.Builder(MainActivity.this)
                .setTitle("登录系统")
                .setView(loginDialog)
                .setPositiveButton("登陆",
                        new DialogInterface.OnClickListener() {
                            @Override
                            public void onClick(DialogInterface dialog,
                                                int which) {
                                final String name = ((EditText) loginDialog
                                        .findViewById(R.id.name)).getText()
                                        .toString();
                                final String pass = ((EditText) loginDialog
                                        .findViewById(R.id.pass)).getText()
                                        .toString();
                                /*final String uri="http://112.237.241.204:8080/Android_Client/servlet/AndroidLoginServler?LoginName=" +
                                        name+"&LoginPassword="+pass;*/
                                final String uri="http://112.237.241.204:8080/Android_Client/servlet/AndroidLoginServler";
                                new Thread() {
                                    @Override
                                    public void run() {
                                        try {
                                            HttpPost post = new HttpPost(uri);
                                            /**
                                             *
                                             定义了一个list,该list的数据类型是NameValuePair(简单名称值对节点类型,
                                             这个代码多处用于Java像url发送Post请求。在发送post请求时用该list来存放参数
                                             */
                                            List params = new
                                                    ArrayList();
                                            params.add(new BasicNameValuePair
                                                    ("LoginName", name));
                                            params.add(new BasicNameValuePair
                                                    ("LoginPassword", pass));
                                            // 设置编码
                                            post.setEntity(new UrlEncodedFormEntity(
                                                    params, HTTP.UTF_8));
                                            HttpResponse response = httpClient
                                                    .execute(post);
                                            // 如果服务器成功返回响应
                                            if (response.getStatusLine()
                                                    .getStatusCode() == 200) {
                                                String msg = EntityUtils
                                                        .toString(response.getEntity());
                                                Looper.prepare();
                                                //显示从服务器返回的信息
                                                Toast.makeText(MainActivity.this,
                                                        msg, Toast.LENGTH_SHORT).show();
                                                Looper.loop();
                                            }
                                        } catch (Exception e) {
                                            e.printStackTrace();
                                        }
                                    }
                                }.start();
                            }
                        }).setNegativeButton("取消", null).show();
    }
}
DSC0000.jpg

DSC0001.jpg

DSC0002.jpg

  

  

  





运维网声明 1、欢迎大家加入本站运维交流群:群②:261659950 群⑤:202807635 群⑦870801961 群⑧679858003
2、本站所有主题由该帖子作者发表,该帖子作者与运维网享有帖子相关版权
3、所有作品的著作权均归原作者享有,请您和我们一样尊重他人的著作权等合法权益。如果您对作品感到满意,请购买正版
4、禁止制作、复制、发布和传播具有反动、淫秽、色情、暴力、凶杀等内容的信息,一经发现立即删除。若您因此触犯法律,一切后果自负,我们对此不承担任何责任
5、所有资源均系网友上传或者通过网络收集,我们仅提供一个展示、介绍、观摩学习的平台,我们不对其内容的准确性、可靠性、正当性、安全性、合法性等负责,亦不承担任何法律责任
6、所有作品仅供您个人学习、研究或欣赏,不得用于商业或者其他用途,否则,一切后果均由您自己承担,我们对此不承担任何法律责任
7、如涉及侵犯版权等问题,请您及时通知我们,我们将立即采取措施予以解决
8、联系人Email:admin@iyunv.com 网址:www.yunweiku.com

所有资源均系网友上传或者通过网络收集,我们仅提供一个展示、介绍、观摩学习的平台,我们不对其承担任何法律责任,如涉及侵犯版权等问题,请您及时通知我们,我们将立即处理,联系人Email:kefu@iyunv.com,QQ:1061981298 本贴地址:https://www.yunweiku.com/thread-637761-1-1.html 上篇帖子: apache+mod-python 下篇帖子: HTTP协议和APACHE服务器
您需要登录后才可以回帖 登录 | 立即注册

本版积分规则

扫码加入运维网微信交流群X

扫码加入运维网微信交流群

扫描二维码加入运维网微信交流群,最新一手资源尽在官方微信交流群!快快加入我们吧...

扫描微信二维码查看详情

客服E-mail:kefu@iyunv.com 客服QQ:1061981298


QQ群⑦:运维网交流群⑦ QQ群⑧:运维网交流群⑧ k8s群:运维网kubernetes交流群


提醒:禁止发布任何违反国家法律、法规的言论与图片等内容;本站内容均来自个人观点与网络等信息,非本站认同之观点.


本站大部分资源是网友从网上搜集分享而来,其版权均归原作者及其网站所有,我们尊重他人的合法权益,如有内容侵犯您的合法权益,请及时与我们联系进行核实删除!



合作伙伴: 青云cloud

快速回复 返回顶部 返回列表