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连接模块代码的更多相关文章

  1. 如何实现android和服务器长连接

    转载 这种功能实际上就是数据同步,同时要考虑手机本身.电量.网络流量等等限制因素,所以通常在移动端上有一下两个解决方案: 1.一种是定时去server查询数据,通常是使用HTTP协议来访问web服务器 ...

  2. Android 心跳包心跳连接 如何实现android和服务器长连接呢?推送消息的原理

    前言:现在的大多数移动端应用都有实时得到消息的能力,简单来说,有发送消息的主动权和接受消息的被动权.例如:微信,QQ,天气预报等等,相信好处和用户体验相信大家都知道吧. 提出问题:这种功能必须涉及cl ...

  3. android 与 服务器通信

    android 与 服务器通信 服务端代码: (1)control 层 /** * 用户登录 * @return */ @RequestMapping(value = "/login&quo ...

  4. 移动开发首页业界资讯移动应用平台技术专题 输入您要搜索的内容 基于Java Socket的自定义协议,实现Android与服务器的长连接(二)

    在阅读本文前需要对socket以及自定义协议有一个基本的了解,可以先查看上一篇文章<基于Java Socket的自定义协议,实现Android与服务器的长连接(一)>学习相关的基础知识点. ...

  5. 阿里云服务器远程连接错误:由于一个协议错误(代码:0x112f),远程会话将被中断。

    2019年10月,阿里云服务器远程连接忽然无法登录.当时正在清理c盘空间,C盘只剩下30+M,忽然远程桌面掉线,以为断网了,再次远程桌面连接时,就出现一下错误. 解决方案:万能的重启!!!具体错误原因 ...

  6. Python远程连接模块-Telnet

    Python远程连接模块-Telnet 作者:尹正杰 版权声明:原创作品,谢绝转载!否则将追究法律责任. 虽然现在主流的python版本还是2.7,相信2020年python程序员都会偏向Python ...

  7. python远程登录服务器(paramiko模块安装和使用)

    转自:http://www.jb51.net/article/46285.htm 一:简介 由paramiko是用python语言写的一个模块,遵循SSH2协议,支持以加密和认证的方式,进行远程服务器 ...

  8. Android客户端网络预连接优化机制探究

    一.背景 一般情况下,我们都是用一些封装好的网络框架去请求网络,对底层实现不甚关注,而大部分情况下也不需要特别关注处理.得益于因特网的协议,网络分层,我们可以只在应用层去处理业务就行.但是了解底层的一 ...

  9. Sql server2012连接Sql server 2008时出现的问题:已成功与服务器建立连接,但在登陆过程中发生错误。(provider:SSL Provider,error:0-接收到的消息异常,或格式不正确。)

    以前连接是正常的,就这两天连不上了.(没有耐心的直接看末尾解决办法) 错误消息如下: 1.尝试读取或写入受保护的内存.这通常指示其他内存已损坏.(System.Data) 2.已成功与服务器建立连接, ...

随机推荐

  1. HDUOJ 2672---god is a girl 《斐波那契数》

    god is a girl Time Limit: 2000/1000 MS (Java/Others)    Memory Limit: 32768/32768 K (Java/Others) To ...

  2. 20145236 冯佳 《Java程序设计》第1周学习总结

    20145236 冯佳 <Java程序设计>第1周学习总结 教材学习内容总结 因为假期在家的时候并没有提前自学Java,所以,这周算是真正开始第一次接触Java.我对Java的了解也仅仅停 ...

  3. plot a critical difference diagram , MATLAB code

    plot a critical difference diagram , MATLAB code 建立criticaldifference函数 function cd = criticaldiffer ...

  4. 452. Minimum Number of Arrows to Burst Balloons——排序+贪心算法

    There are a number of spherical balloons spread in two-dimensional space. For each balloon, provided ...

  5. centos 5.8 64位系统安装 mysql5.6

    mysql5.5以上的版本编译需要 cmake         1 .安装cmake wget http://www.cmake.org/files/v2.8/cmake-2.8.10.2.tar.g ...

  6. 关于python中的编码:unicode, utf-8, gb2312

    计算机早期是只支持ASCII码的,经过long long的发展,出现了这些支持世界上各种语言字符的编码:unicode, utf-8, gb2312. 对于unicode, utf-8, gb2312 ...

  7. jsp标签之<%%>和<%!%>

    <%! %>中声明的是全局变量,不过写前面最好<% %>中声明的是局部变量.<%=%>一般表达式,输出某一变量的值.例如:<%! String totalSt ...

  8. TableLayout练习

    <?xml version="1.0" encoding="utf-8"?> <TableLayout xmlns:android=" ...

  9. Deep Learning In NLP 神经网络与词向量

    0. 词向量是什么 自然语言理解的问题要转化为机器学习的问题,第一步肯定是要找一种方法把这些符号数学化. NLP 中最直观,也是到目前为止最常用的词表示方法是 One-hot Representati ...

  10. [开发笔记]-“在引用COM组件时,出现了无法嵌入互操作类型。。。”的错误

    这两天在做一个需要将wps文档转换成word文档的程序,在调用wps的com组件时项目编译是没有问题的,但当运行的时候却弹出了下面的错误提示: 从网上百度一番后,找到了正确的解决方法. 先从Com组件 ...