本地不带服务器调用没有问题 英文,启动服务在Servlet中实例化HttpClientGetter调用getData时报错

> jeffsui的博客详情
摘要: android与server端交互的小demo,客户端发送json数据,服务器端根据数据库中的记录,返回对应的字符串,客户端解析后,显示相关内容。
朋友让写一个关于android与server端servlet交互的demo,比项目中的例子要简单很多,入门的朋友可以参考下。
1.服务器端Servlet
核心代码:
* 项目名称 JSONDemo
名 servlet
名 CustomerServlet.java
人 Administrator
* 描述信息 客户端验证用户登陆Servlet
* 发布日期 下午03:28:47
* 修改日期
* 版本信息 V1.0
public class CustomerServlet extends HttpServlet {
private static final long serialVersionUID = 387358L;
protected void doPost(HttpServletRequest req, HttpServletResponse resp)
throws ServletException, IOException {
//登陆成功标志
String LOGIN_FLAG="";
//获得客户端提交用户名密码
String username = req.getParameter("username");
String password = req.getParameter("password");
//调用UserDAO中isLogin方法判断数据中用户名密码是否正确
boolean flag=UserDAO.isLogin(username, password);
DataOutputStream output=new DataOutputStream(resp.getOutputStream());
if (flag) {
LOGIN_FLAG="success";
output.writeUTF("服务器端数据:"+LOGIN_FLAG);
System.out.println(LOGIN_FLAG);
output.writeInt(1);
output.close();
//登录失败
LOGIN_FLAG="failure";
System.out.println(LOGIN_FLAG);
output.writeUTF("服务器端数据:"+LOGIN_FLAG);
output.close();
} catch (Exception e) {
e.printStackTrace();
2.android客户端
ClientDemo 核心代码:
public class MainActivity extends Activity {
//private static final int REQUEST_CODE = 2;
HttpPost httpRequest=new HttpPost(UriAPI.HTTPCustomer);
EditText et_
EditText et_
TextView show_
Button btn_
Button btn_
ProgressDialog progressD
/** Called when the activity is first created. */
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
//初始化登陆界面
btn_login=(Button) findViewById(R.id.btn_login);
btn_cancle=(Button) findViewById(R.id.btn_cancle);
et_name=(EditText) findViewById(R.id.et_name);
et_pwd = (EditText) findViewById(R.id.et_pwd);
show_login=(TextView) findViewById(R.id.show_login);
progressDialog = new ProgressDialog(this);
btn_login.setOnClickListener(new OnClickListener() {
@SuppressWarnings("unchecked")
public void onClick(View v) {
//通过AsyncTask类提交数据 异步显示
new AT().execute(et_name.getText().toString(),et_pwd.getText().toString());
public class UriAPI {
/** 定义一个Uri **/
public static final String HTTPCustomer ="http://10.0.1.9:8026/JSONDemo/servlet/CustomerServlet";
@SuppressWarnings("rawtypes")
class AT extends AsyncTask{
String result="";
protected void onPreExecute() {
//加载progressDialog
progressDialog.show();
protected Object doInBackground(Object... params_obj) {
CharSequence username="";
CharSequence password="";
username=et_name.getText();
password =et_pwd.getText();
if(!username.equals("")&&!password.equals("")){
//请求数据
HttpPost httpRequest
= new HttpPost(UriAPI.HTTPCustomer);
//创建参数
List&NameValuePair& params=new ArrayList&NameValuePair&();
params.add(new BasicNameValuePair("username", username.toString()));
params.add(new BasicNameValuePair("password", password.toString()));
//params.add(new BasicNameValuePair("flag","0"));
//对提交数据进行编码
httpRequest.setEntity(new UrlEncodedFormEntity(params,HTTP.UTF_8));
HttpResponse httpResponse=new DefaultHttpClient().execute(httpRequest);
//获取响应服务器的数据
if (httpResponse.getStatusLine().getStatusCode()==200) {
//利用字节数组流和包装的绑定数据
byte[] data =new byte[2048];
//先把从服务端来的数据转化成字节数组
data =EntityUtils. toByteArray((HttpEntity)httpResponse.getEntity());
//再创建字节数组输入流对象
ByteArrayInputStream bais = new ByteArrayInputStream(data);
//绑定字节流和数据包装流
DataInputStream dis = new DataInputStream(bais);
//将字节数组中的数据还原成原来的各种数据类型,代码如下:
result=new String(dis.readUTF());
Log.i("服务器返回信息:", result);
} catch(ClientProtocolException e){
e.printStackTrace();
}catch(UnsupportedEncodingException e){
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
protected void onPostExecute(Object result) {
//获得服务器返回信息成功后
show_login.setText(result.toString());
//取消进度条
progressDialog.cancel();
3.界面截图
3.1 未登录
3.2 登陆中
3.3 登陆成功
3.4 登陆失败
&4.代码下载
人打赏支持
码字总数 73809
恩 留邮箱 发给你
已发送,请查收!
以发送,望查收!
已经发送,望查收!
已发送,请查收!
已发送,请查收!多谢
已经发送,望查收!
我换成百度网盘了,可以下载!
文章最后提供了网盘下载啊
支付宝支付
微信扫码支付
打赏金额: ¥
已支付成功
打赏金额: ¥
& 开源中国(OSChina.NET) |
开源中国社区(OSChina.net)是工信部
指定的官方社区HttpClient跨项目(跨服务器)调用方法例子
package XX.XX.XX;
import java.util.ArrayL
import java.util.Limport org.apache.http.NameValueP
import org.apache.http.client.HttpC
import org.apache.http.client.ResponseH
import org.apache.http.client.entity.UrlEncodedFormE
import org.apache.http.client.methods.HttpG
import org.apache.http.client.methods.HttpP
import org.apache.http.impl.client.BasicResponseH
import org.apache.http.impl.client.DefaultHttpC
import org.apache.http.message.BasicNameValueP
public class HttpClientTest {
public static void main(String[] args) {
* @Description: 以post方式请求网页
public static void myPost(){
String url = &http://127.0.0.1:8080/testssi/MyTest.action&;
//创建一个默认的HttpClient
HttpClient httpclient = new DefaultHttpClient();
//以post方式请求网页
HttpPost httppost = new HttpPost(url);
//添加HTTP POST参数
List &NameValuePair& nvps = new ArrayList &NameValuePair&();
nvps.add(new BasicNameValuePair(&username&, &cz&));
nvps.add(new BasicNameValuePair(&password&, &123&));
//将POST参数以UTF-8编码并包装成表单实体对象
httppost.setEntity(new UrlEncodedFormEntity(nvps, &UTF-8&));
//打印请求地址
System.out.println(&executing request & + httppost.getRequestLine().getUri());
//创建响应处理器处理服务器响应内容
ResponseHandler&String& responseHandler = new BasicResponseHandler();
//执行请求并获取结果
String responseBody = httpclient.execute(httppost, responseHandler);
System.out.println(responseBody);
}catch(Exception e){
e.printStackTrace();
}finally {
// 当不再需要HttpClient实例时,关闭连接管理器以确保释放所有占用的系统资源
httpclient.getConnectionManager().shutdown();
* @Description: 以get方式请求网页
public static void myGet(){
String url = &http://127.0.0.1:8080/testssi/MyTest.action&;
//创建一个默认的HttpClient
HttpClient httpclient = new DefaultHttpClient();
//以get方式请求网页
HttpGet httpget = new HttpGet(url);
//打印请求地址
System.out.println(&executing request & + httpget.getURI());
//创建响应处理器处理服务器响应内容
ResponseHandler&String& responseHandler = new BasicResponseHandler();
//执行请求并获取结果
String responseBody = httpclient.execute(httpget, responseHandler);
System.out.println(responseBody);
}catch(Exception e){
e.printStackTrace();
}finally {
// 当不再需要HttpClient实例时,关闭连接管理器以确保释放所有占用的系统资源
httpclient.getConnectionManager().shutdown();
参考知识库
* 以上用户言论只代表其个人观点,不代表CSDN网站的观点或立场
访问:7618次
排名:千里之外
(1)(2)(2)(1)(1)(2)(1)(4)(6)  在Android中,我们可以通过使用标准的Java接口来完成Android应用程序的联网操作。但是在实际开发中,可能会需要用到更复杂的联网操作,为此,Android平台提供了Apache&HttpClient接口,为客户端的HTTP编程提供了高效、便捷、功能丰富的工具包支持。
  Android平台在引入Apache&HttpClient的同时,还对其进行了一些封装和扩展,如设置缺省的HTTP超时和缓存大小等。使用Apache&HttpClient接口,我们可以创建HttpClient、HttpGet/HttpPost、HttpResponse等对象,设置连接参数,执行HTTP操作,处理服务器返回结果等。
  本文将以两个实例演示在Android开发中如何使用HttpClient接口完成客户端HTTP编程。其中,一个实例使用GET方式获取服务器上的图片进行显示;一个实例使用POST方式向服务器提交数据,完成登录功能。
1.常用的接口和类
  在讲解实例之前,我们有必要先了解一下在HttpClient接口中,为我们提供了哪些常用的接口和类。
1.1&ClientConnectionManager接口
  ClientConnectionManager是客户端连接管理器接口,用于对连接到服务器上的客户端进行管理,主要提供了以下6个抽象方法:
  (1)abstract&void&closeExpiredConnections();
  (2)abstract&void&closeIdleConnections(long&idletime,&TimeUnit&tunit);
  (3)abstract&SchemeRegistry&getSchemeRegistry();
  (4)abstract&void&releaseConnection(ManagedClientConnection&conn,&long&validDuration,&TimeUnit&timeUnit);
  (5)abstract&ClientConnectionRequest&requestConnection(HttpRoute&route,&Object&state);&
  (6)abstract&void&shutdown();
  其中,closeExpiredConnections()方法用于关闭所有过期的连接;closeIdleConnections()方法用于关闭所有空闲的连接;getSchemeRegistry()方法用于获得注册方案;releaseConnection()方法用于释放连接;requestConnection()方法用于请求一个新的连接;shutdown()方法用于关闭管理器并释放资源。
1.2&DefaultHttpClient
  DefaultHttpClient是HttpClient接口的一个直接子类,它是一个默认的HTTP客户端,通常我们可以使用它来创建一个HTTP连接。在HttpClient接口中提供了多个重载的execute()方法,用来执行HTTP请求。
1.3&HttpRequest接口
  HttpGet和HttpPost都是HttpRequest接口的直接子类,分别用于向服务器提交GET请求和POST请求。
1.4&HttpResponse接口
  HttpResponse接口提供了HTTP的响应信息,其主要方法如图1所示。
图1&HttpResponse接口提供的主要方法
  其中,getEntity()方法用于获取响应的消息实体;getStatusLine()方法用于获取响应的状态行,在返回结果StatusLine对象中包含了HTTP响应的状态码,可以使用方法getStatusCode()获得。
2.使用GET方式获取服务器上的图片
  在该实例中,我们使用了在上一篇博文《》中搭建好的Web工程作为服务器,并在该工程中添加了一张名为&cat.jpg&的图片作为我们将要获取的对象。
  使用GET方式获取服务器上的图片,可以按照以下4个步骤进行:
  (1)创建一个GET方式的HttpRequest请求对象。
  (2)创建一个默认的HTTP客户端,并执行该GET方式的HTTP请求。
  (3)获得服务器的响应码,据此判断服务器是否正确响应。
  (4)获得服务器的响应内容(InputStream),转换成Bitmap图片。
  以上4个步骤的具体实现代码如下:
* Function
发送GET请求
博客园-依旧淡然
public static Bitmap sendGetResquest(String path) {
Bitmap bitmap = null;
HttpGet httpGet = new HttpGet(path);
//创建一个GET方式的HttpRequest对象
DefaultHttpClient httpClient = new DefaultHttpClient();
//创建一个默认的HTTP客户端
HttpResponse httpResponse = httpClient.execute(httpGet);
//执行GET方式的HTTP请求
int reponseCode = httpResponse.getStatusLine().getStatusCode();
//获得服务器的响应码
if(reponseCode == HttpStatus.SC_OK) {
InputStream inputStream = httpResponse.getEntity().getContent();
//获得服务器的响应内容
bitmap = BitmapFactory.decodeStream(inputStream);
inputStream.close();
} catch (ClientProtocolException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
  最后,我们在Activity中通过一个Button按钮来向服务器发送GET请求,并调用sendGetResquest()方法将得到的Bitmap对象显示在ImageView控件中。具体的实现代码如下:
* Function
点击事件响应
博客园-依旧淡然
public void onClick(View view) {
switch(view.getId()) {
case R.id.button_get:
String url = "http://192.168.1.101:8080/myhttp/cat.jpg";
Bitmap bitmap = HttpUtils.sendGetResquest(url);
mImageView.setImageBitmap(bitmap);
  运行该工程,点击&提交GET请求&按钮后,可以看到如图2所示的显示界面,在&提交GET请求&按钮的下面所显示的图片正是我们从服务器上得到的图片。
图2&使用方式获取服务器上的图片
3.使用POST方式向服务器提交数据
  在该实例中,我们同样使用了在上一篇博文《》中搭建好的Web工程作为服务器。运行Tomcat,在浏览器中访问该Web工程,可以看到如图3所示的界面。&
图3&Web工程的显示页面
  该实例要做的就是,使用POST方式向服务器提交用户名和密码,模拟登录过程,并获得服务器的验证信息,显示登录是否成功。
  使用POST方式向服务器提交数据,比GET方式要稍微复杂点,具体可以按照以下5个步骤进行:
  (1)对请求体参数(也就是username和password)进行封装。
  (2)创建一个POST方式的HttpRequest对象,并设置POST方式的请求体。
  (3)创建一个默认的HTTP客户端,并执行该POST方式的HTTP请求。
  (4)获得服务器的响应码,据此判断服务器是否正确响应。
  (5)获得服务器的响应内容(InputStream),转换成String字符串进行显示。
  以上5个步骤的具体实现代码如下:
* Function
发送POST请求
博客园-依旧淡然
public static String sendPostResquest(String path, Map&String, String& params, String encoding) {
List&NameValuePair& list = new ArrayList&NameValuePair&();
//封装请求体参数
if((params != null) && !params.isEmpty()) {
for(Map.Entry&String, String& param : params.entrySet()) {
list.add(new BasicNameValuePair(param.getKey(), param.getValue()));
UrlEncodedFormEntity entity = new UrlEncodedFormEntity(list, encoding);
//对请求体参数进行URL编码
HttpPost httpPost = new HttpPost(path);
//创建一个POST方式的HttpRequest对象
httpPost.setEntity(entity);
//设置POST方式的请求体
DefaultHttpClient client = new DefaultHttpClient();
HttpResponse httpResponse = client.execute(httpPost);
//执行POST请求
int reponseCode = httpResponse.getStatusLine().getStatusCode();
//获得服务器的响应码
if(reponseCode == HttpStatus.SC_OK) {
String resultData = EntityUtils.toString(httpResponse.getEntity());
//获得服务器的响应内容
return resultD
} catch (IOException e) {
e.printStackTrace();
return "";
  同样的,我们在Activity中通过一个Button按钮来向服务器发送POST请求,并调用sendPostResquest()方法将得到的服务器响应结果显示在TextView控件中。具体的实现代码如下:
* Function
点击事件响应
博客园-依旧淡然
public void onClick(View view) {
switch(view.getId()) {
case R.id.button_submit:
String username = mEditText_userName.getText().toString();
String password = mEditText_password.getText().toString();
Map&String, String& params = new HashMap&String, String&();
params.put("username", username);
params.put("password", password);
String url = "http://192.168.1.101:8080/myhttp/servlet/LoginAction";
mTextView_result.setText(HttpUtils.sendPostResquest(url, params, "utf-8"));
  运行该工程,在EditText控件中分别输入用户名和密码,点击&提交数据&按钮后,可以看到如图4所示的显示界面,在&提交数据&按钮下面的TextView控件中可以看到服务器返回了&Login&succeeded!&&的提示信息。
阅读(...) 评论()探讨:使用httpClient在客户端与服务器端传输对象参数的详解
字体:[ ] 类型:转载 时间:
本篇文章是对使用httpClient在客户端与服务器端传输对象参数进行了详细的分析介绍,需要的朋友参考下
昨天把httpClient的源代码下载来看了一下。 稍微跟踪了一下,最终还是使用java.net包的东西.不过封装的实在是漂亮.写程序方便多了。不过还是建议最好先熟悉net包下的东西.为了测试写了个在客户端和服务器段传对象的代码. 简单的传递了一个字符串. 如果复杂点可以传其他的对象,在参数里给出class name之类的信息.服务器端就可以使用反射来做一些实用的操作了。客户端: 代码如下:import java.io.IOEimport java.io.Simport mons.httpclient.HttpCimport mons.httpclient.methods.InputStreamRequestEimport mons.httpclient.methods.PostMimport mons.httpclient.methods.RequestEpublic class MyTest{&&& /**&&&& * @param args&&&& * @throws IOException&&&& * @throws ClassNotFoundException&&&& */&&& public static void main(String[] args) throws IOException, ClassNotFoundException&&& {&&&&&&& String url = "http://localhost:8084/system/linantest";&&&&&&& String queryString = "test=hello";&&&&&&& String inputObj = " boy!";&&&&&&& Serializable s = getObjFromServer(url, queryString, inputObj);&&&&&&& System.out.println(s.toString());&&& }&&& /**&&&& * @param url&&&& * @param queryString 类似a=b&c=d 形式的参数&&&& * &&&& * @param inputObj&& 发送到服务器的对象。&&&& *&&&& &&&& * @return 服务器返回到客户端的对象。&&&& * @throws IOException&&&& */&&& public static Serializable getObjFromServer(String url, String queryString, Serializable inputObj) throws IOException&&& {&&&&&&& HttpClient client = new HttpClient();&&&&&&& PostMethod post = new PostMethod(url);&&&&&&& post.setQueryString(queryString);&&&&&&& post.setRequestHeader("Content-Type", "application/octet-stream");&&&&&&& java.io.ByteArrayOutputStream bOut = new java.io.ByteArrayOutputStream(1024);&&&&&&& java.io.ByteArrayInputStream bInput =&&&&&&& java.io.ObjectOutputStream out =&&&&&&& Serializable returnObj =&&&&&&& try&&&&&&& {&&&&&&&&&&& out = new java.io.ObjectOutputStream(bOut);&&&&&&&&&&& out.writeObject(inputObj);&&&&&&&&&&& out.flush();&&&&&&&&&&& out.close();&&&&&&&&&&& out =&&&&&&&&&&& bInput = new java.io.ByteArrayInputStream(bOut.toByteArray());&&&&&&&&&&& RequestEntity re = new InputStreamRequestEntity(bInput);&&&&&&&&&&& post.setRequestEntity(re);&&&&&&&&&&& client.executeMethod(post);&&&&&&&&&&& java.io.InputStream in = post.getResponseBodyAsStream();&&&&&&&&&&& java.io.ObjectInputStream oInput = new java.io.ObjectInputStream(in);&&&&&&&&&&& returnObj = (Serializable) oInput.readObject();&&&&&&&&&&& oInput.close();&&&&&&&&&&& oInput =&&&&&&& }&&&&&&& catch (IOException e)&&&&&&& {&&&&&&&&&&& // TODO Auto-generated catch block&&&&&&&&&&& e.printStackTrace();&&&&&&& }&&&&&&& catch (ClassNotFoundException e)&&&&&&& {&&&&&&&&&&& // TODO Auto-generated catch block&&&&&&&&&&& e.printStackTrace();&&&&&&& }&&&&&&& finally&&&&&&& {&&&&&&&&&&& if (out != null)&&&&&&&&&&& {&&&&&&&&&&&&&&& out.close();&&&&&&&&&&&&&&& out =&&&&&&&&&&& }&&&&&&&&&&& if (bInput != null)&&&&&&&&&&& {&&&&&&&&&&&&&&& bInput.close();&&&&&&&&&&&&&&& bInput =&&&&&&&&&&& }&&&&&&&&&&& //释放连接&&&&&&&&&&& post.releaseConnection();&&&&&&& }&&&&&&& return returnO&&& }}服务器端的servlet 代码如下:package test.import java.io.IOEimport javax.servlet.ServletEimport javax.servlet.http.HttpSimport javax.servlet.http.HttpServletRimport javax.servlet.http.HttpServletRimport org.openjweb.eai.adapter.TimerDBApublic class TestServlet extends HttpServlet{&&& public TestServlet()&&& {&&&&&&& super();&&& }&&& /**&&&& * Destruction of the servlet. &br&&&&& */&&& public void destroy()&&& {&&&&&&& super.destroy(); // Just puts "destroy" string in log&&&&&&& // Put your code here&&& }&&& /**&&&& * The doGet method of the servlet. &br&&&&& * &&&& * This method is called when a form has its tag value method equals to get.&&&& * &&&& * @param request&&&& *&&&&&&&&&&& the request send by the client to the server&&&& * @param response&&&& *&&&&&&&&&&& the response send by the server to the client&&&& * @throws Exception&&&& */&&& public void doGet(HttpServletRequest request, HttpServletResponse response)&&& {&&&&&&& String test = request.getParameter("test");&&&&&&& java.io.ObjectInputStream oi =&&&&&&& java.io.ObjectOutputStream ot =&&&&&&& try&&&&&&& {&&&&&&&&&&& oi = new java.io.ObjectInputStream(request.getInputStream());&&&&&&&&&&& Object o = oi.readObject();&&&&&&&&&&& oi.close();&&&&&&&&&&& oi =&&&&&&&&&&& String outObj = test + o.toString();&&&&&&&&&&& ot = new java.io.ObjectOutputStream(response.getOutputStream());&&&&&&&&&&& ot.writeObject(outObj);&&&&&&&&&&& ot.flush();&&&&&&&&&&& ot.close();&&&&&&&&&&& ot =&&&&&&& }&&&&&&& catch (IOException e)&&&&&&& {&&&&&&&&&&& // TODO Auto-generated catch block&&&&&&&&&&& e.printStackTrace();&&&&&&& }&&&&&&& catch (ClassNotFoundException e)&&&&&&& {&&&&&&&&&&& // TODO Auto-generated catch block&&&&&&&&&&& e.printStackTrace();&&&&&&& }&&&&&&& finally&&&&&&& {&&&&&&&&&&& try&&&&&&&&&&& {&&&&&&&&&&&&&&& if (oi != null)&&&&&&&&&&&&&&& {&&&&&&&&&&&&&&&&&&& oi.close();&&&&&&&&&&&&&&&&&&& oi =&&&&&&&&&&&&&&& }&&&&&&&&&&&&&&& if (ot != null)&&&&&&&&&&&&&&& {&&&&&&&&&&&&&&&&&&& ot.close();&&&&&&&&&&&&&&&&&&& ot =&&&&&&&&&&&&&&& }&&&&&&&&&&& }&&&&&&&&&&& catch (IOException e)&&&&&&&&&&& {&&&&&&&&&&&&&&& // TODO Auto-generated catch block&&&&&&&&&&&&&&& e.printStackTrace();&&&&&&&&&&& }&&&&&&& }&&&&&&& }&&& /**&&&& * The doPost method of the servlet. &br&&&&& * &&&& * This method is called when a form has its tag value method equals to&&&& * post.&&&& * &&&& * @param request&&&& *&&&&&&&&&&& the request send by the client to the server&&&& * @param response&&&& *&&&&&&&&&&& the response send by the server to the client&&&& * @throws ServletException&&&& *&&&&&&&&&&&& if an error occurred&&&& * @throws IOException&&&& *&&&&&&&&&&&& if an error occurred&&&& */&&& public void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException&&& {&&&&&&& doGet(request, response);&&& }&&& /**&&&& * Initialization of the servlet. &br&&&&& * &&&& * @throws ServletException&&&& *&&&&&&&&&&&& if an error occure&&&& */&&& public void init() throws ServletException&&& {&&&&&&& // Put your code here&&& }}
您可能感兴趣的文章:
大家感兴趣的内容
12345678910
最近更新的内容
常用在线小工具

我要回帖

更多关于 httpclient与servlet 的文章

 

随机推荐