Android与服务器http连接模块代码
package com.example.httpdemo2; import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.UnsupportedEncodingException;
import java.util.ArrayList;
import java.util.List; 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 android.os.Bundle;
import android.app.Activity;
import android.util.Log;
import android.view.Menu;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.EditText;
import android.widget.TextView; public class HttpDemo2Activity extends Activity
{
private String TAG = "http";
private EditText mNameText = null;
private EditText mAgeText = null; private Button getButton = null;
private Button postButton = null; private TextView mResult = null; // 基本地址:服务器ip地址:端口号/Web项目逻辑地址+目标页面(Servlet)的url-pattern
private String baseURL = "http://192.168.11.6:8080/HelloWeb/servlet/WelcomeUserServlet"; @Override
protected void onCreate(Bundle savedInstanceState)
{
Log.i(TAG, "onCreate");
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_http_demo2); mNameText = (EditText) findViewById(R.id.name);
mAgeText = (EditText) findViewById(R.id.age);
mResult = (TextView) findViewById(R.id.result); getButton = (Button) findViewById(R.id.submit_get);
getButton.setOnClickListener(mGetClickListener);
postButton = (Button) findViewById(R.id.submit_post);
postButton.setOnClickListener(mPostClickListener);
} private OnClickListener mGetClickListener = new View.OnClickListener()
{ @Override
public void onClick(View v)
{
Log.i(TAG, "GET request");
// 先获取用户名和年龄
String name = mNameText.getText().toString();
String age = mAgeText.getText().toString(); // 使用GET方法发送请求,需要把参数加在URL后面,用?连接,参数之间用&分隔
String url = baseURL + "?username=" + name + "&age=" + age; // 生成请求对象
HttpGet httpGet = new HttpGet(url);
HttpClient httpClient = new DefaultHttpClient(); // 发送请求
try
{ HttpResponse response = httpClient.execute(httpGet); // 显示响应
showResponseResult(response);// 一个私有方法,将响应结果显示出来 }
catch (Exception e)
{
e.printStackTrace();
} }
}; private OnClickListener mPostClickListener = new View.OnClickListener()
{ @Override
public void onClick(View v)
{
Log.i(TAG, "POST request");
// 先获取用户名和年龄
String name = mNameText.getText().toString();
String age = mAgeText.getText().toString(); NameValuePair pair1 = new BasicNameValuePair("username", name);
NameValuePair pair2 = new BasicNameValuePair("age", age); List<NameValuePair> pairList = new ArrayList<NameValuePair>();
pairList.add(pair1);
pairList.add(pair2); try
{
HttpEntity requestHttpEntity = new UrlEncodedFormEntity(
pairList);
// URL使用基本URL即可,其中不需要加参数
HttpPost httpPost = new HttpPost(baseURL);
// 将请求体内容加入请求中
httpPost.setEntity(requestHttpEntity);
// 需要客户端对象来发送请求
HttpClient httpClient = new DefaultHttpClient();
// 发送请求
HttpResponse response = httpClient.execute(httpPost);
// 显示响应
showResponseResult(response);
}
catch (Exception e)
{
e.printStackTrace();
} }
}; /**
* 显示响应结果到命令行和TextView
* @param response
*/
private void showResponseResult(HttpResponse response)
{
if (null == response)
{
return;
} HttpEntity httpEntity = response.getEntity();
try
{
InputStream inputStream = httpEntity.getContent();
BufferedReader reader = new BufferedReader(new InputStreamReader(
inputStream));
String result = "";
String line = "";
while (null != (line = reader.readLine()))
{
result += line; } System.out.println(result);
mResult.setText("Response Content from server: " + result);
}
catch (Exception e)
{
e.printStackTrace();
} } }
布局文件:
<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" > <TextView
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:text="Username:" /> <EditText
android:id="@+id/name"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:inputType="text" /> <TextView
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:text="User Age:" /> <EditText
android:id="@+id/age"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:inputType="number" /> <Button
android:id="@+id/submit_get"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:text="Submit using GET" /> <Button
android:id="@+id/submit_post"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:text="Submit using POST" /> <TextView
android:id="@+id/result"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:textColor="#0000FF"
android:textSize="14sp" >
</TextView> </LinearLayout>
须在androidMenifest中配置联网权限;
Android与服务器http连接模块代码的更多相关文章
- 如何实现android和服务器长连接
转载 这种功能实际上就是数据同步,同时要考虑手机本身.电量.网络流量等等限制因素,所以通常在移动端上有一下两个解决方案: 1.一种是定时去server查询数据,通常是使用HTTP协议来访问web服务器 ...
- Android 心跳包心跳连接 如何实现android和服务器长连接呢?推送消息的原理
前言:现在的大多数移动端应用都有实时得到消息的能力,简单来说,有发送消息的主动权和接受消息的被动权.例如:微信,QQ,天气预报等等,相信好处和用户体验相信大家都知道吧. 提出问题:这种功能必须涉及cl ...
- android 与 服务器通信
android 与 服务器通信 服务端代码: (1)control 层 /** * 用户登录 * @return */ @RequestMapping(value = "/login&quo ...
- 移动开发首页业界资讯移动应用平台技术专题 输入您要搜索的内容 基于Java Socket的自定义协议,实现Android与服务器的长连接(二)
在阅读本文前需要对socket以及自定义协议有一个基本的了解,可以先查看上一篇文章<基于Java Socket的自定义协议,实现Android与服务器的长连接(一)>学习相关的基础知识点. ...
- 阿里云服务器远程连接错误:由于一个协议错误(代码:0x112f),远程会话将被中断。
2019年10月,阿里云服务器远程连接忽然无法登录.当时正在清理c盘空间,C盘只剩下30+M,忽然远程桌面掉线,以为断网了,再次远程桌面连接时,就出现一下错误. 解决方案:万能的重启!!!具体错误原因 ...
- Python远程连接模块-Telnet
Python远程连接模块-Telnet 作者:尹正杰 版权声明:原创作品,谢绝转载!否则将追究法律责任. 虽然现在主流的python版本还是2.7,相信2020年python程序员都会偏向Python ...
- python远程登录服务器(paramiko模块安装和使用)
转自:http://www.jb51.net/article/46285.htm 一:简介 由paramiko是用python语言写的一个模块,遵循SSH2协议,支持以加密和认证的方式,进行远程服务器 ...
- Android客户端网络预连接优化机制探究
一.背景 一般情况下,我们都是用一些封装好的网络框架去请求网络,对底层实现不甚关注,而大部分情况下也不需要特别关注处理.得益于因特网的协议,网络分层,我们可以只在应用层去处理业务就行.但是了解底层的一 ...
- Sql server2012连接Sql server 2008时出现的问题:已成功与服务器建立连接,但在登陆过程中发生错误。(provider:SSL Provider,error:0-接收到的消息异常,或格式不正确。)
以前连接是正常的,就这两天连不上了.(没有耐心的直接看末尾解决办法) 错误消息如下: 1.尝试读取或写入受保护的内存.这通常指示其他内存已损坏.(System.Data) 2.已成功与服务器建立连接, ...
随机推荐
- 实验二Step1-有序顺序表
#include<stdio.h> struct job { ];//作业名称 char status;//当前状态 int arrtime;//到达时间 int reqtime;//要求 ...
- html 标签总结
<q>标签,短文本引用 例如“聪明秀出为之英,胆略过人为之雄.” <blockquote>标签,长文本引用 <blockquote>标签的解析是缩进样式. 没有HT ...
- JMeter基础知识
JMeter介绍 JMeter是开源的性能测试工具和接口测试工具,工作原理和Loadrunner一样:作为浏览器和WebServer之间的网关,捕获Browser请求和WebServer响应,然后通过 ...
- (01)odoo模型中调用窗体动作
*模型代码 addons/stock/stock.py ---------------- #移库单执行移库动作(弹出详细框) @api.cr_uid_ids_context def ...
- iOS开发中深入理解CADisplayLink和NSTimer
一.什么是CADisplayLink 简单地说,它就是一个定时器,每隔几毫秒刷新一次屏幕. CADisplayLink是一个能让我们以和屏幕刷新率相同的频率将内容画到屏幕上的定时器.我们在应用中创建一 ...
- Oracle 中的 decode
含义解释:decode(条件,值1,返回值1,值2,返回值2,...值n,返回值n,缺省值) 该函数的含义如下:IF 条件=值1 THEN RETURN(翻译值1)ELSIF 条件=值2 THEN R ...
- 如何实现ASP.NET中网站访问量的统计
如何实现ASP.NET中网站访问量的统计 2009-07-30 15:50 佚名 网翼教程网 字号:T | T 本文介绍了如何在asp.net中进行网站访问量的统计. AD:51CTO 网+ 第十二期 ...
- 用Navicat for MYsql创建表,插入中文显乱码
段都有编码设置.出现乱码肯定是你现在用的编码混乱造成的 解决办法: 第一步 先改数据库编码 先修改你的数据库,如果你页面用的是UTF-8编码那么你数据库内的编码也需要设置为UTF-8,每个字段都需要设 ...
- SA 的参数
SA 的参数也只能是常数数组. http://www.cnblogs.com/del/archive/2009/10/27/1590692.html ja := SA([]); jo := SO(); ...
- PC客户端测试总结
1.1界面显示内容的检查l 完整性(1显示时应考虑数据显示宽度的自适应或自动换行(数据长度较长).(2所数据展现的界面(如查询等),必须使测试数据的记录数超过一页,以验证满页时其窗体是否有横向.纵向滚 ...