通过昨天对HttpClient的学习,今天封装了HttpClient类

代码如下:

package com.tp.soft.util;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.util.ArrayList;
import java.util.List;
import java.util.Map; import org.apache.http.HttpResponse;
import org.apache.http.HttpStatus;
import org.apache.http.NameValuePair;
import org.apache.http.client.ClientProtocolException;
import org.apache.http.client.HttpClient;
import org.apache.http.client.entity.UrlEncodedFormEntity;
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; public class HttpUtil {
public static String postRequest(String serverPath, Map<String, String> params, String encoding){
List<NameValuePair> paramPair = new ArrayList<NameValuePair>();
if(params != null && !params.isEmpty()){
for(Map.Entry<String, String> entry : params.entrySet()){
paramPair.add(new BasicNameValuePair(entry.getKey(), entry.getValue()));
}
}
try {
HttpClient client = new DefaultHttpClient();
HttpPost post = new HttpPost(serverPath);
post.setEntity(new UrlEncodedFormEntity(paramPair, HTTP.UTF_8));
HttpResponse response = client.execute(post);
if(response.getStatusLine().getStatusCode() == HttpStatus.SC_OK){
BufferedReader br = new BufferedReader(new InputStreamReader(response.getEntity().getContent()));
//数据
String reqData = null;
String responseData = "";
while((reqData = br.readLine()) != null){
responseData += reqData;
}
br.close();
return responseData;
}
} catch (ClientProtocolException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
return "postRequest error";
}
}

然后通过调用HttpUtil类来达成与服务器交互

package com.tp.soft.app;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map; import android.app.Activity;
import android.os.Bundle;
import android.view.LayoutInflater;
import android.view.Menu;
import android.view.View;
import android.view.ViewGroup;
import android.widget.BaseAdapter;
import android.widget.ListView;
import android.widget.TextView; import com.google.gson.Gson;
import com.google.gson.reflect.TypeToken;
import com.tp.soft.entity.User;
import com.tp.soft.util.HttpUtil; public class MainActivity extends Activity { private ListView mListView;
private TextView mContentTxt;
private TextView mTimeTxt; private String serverPath = "http://122.226.178.54:8080/uploadApp/LoginServlet";
private static final String ENCODING = "utf-8";
private List<User> userList;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
loadList();
mListView = (ListView) findViewById(R.id.list_id);
mListView.setAdapter(new BaseAdapter() { @Override
public View getView(int position, View convertView, ViewGroup parent) {
if(null == convertView){
convertView = LayoutInflater.from(getApplicationContext()).inflate(R.layout.item, null);
} TextView textView = (TextView) convertView.findViewById(R.id.contentTxt);
textView.setText(userList.get(position).getUsername());
return convertView;
} @Override
public long getItemId(int position) {
return position;
} @Override
public Object getItem(int position) {
return position;
} @Override
public int getCount() {
return userList.size();
}
});
} private List<User> loadList() {
Map<String, String> params = new HashMap<String, String>();
String data = HttpUtil.postRequest(serverPath, params, ENCODING);
userList = new Gson().fromJson(data, new TypeToken<List<User>>() {}.getType());
return userList;
} @Override
public boolean onCreateOptionsMenu(Menu menu) {
getMenuInflater().inflate(R.menu.main, menu);
return true;
}
}

服务器端则采用了servlet

protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
response.setCharacterEncoding("utf-8");
String uname = request.getParameter("uname");
String pwd = request.getParameter("pwd"); PrintWriter pw = response.getWriter();
Gson gson = new GsonBuilder().create();
List<User> userList = new ArrayList<User>();
User user = new User();
user.setUsername("zs");
user.setPassword("");
userList.add(user); User user1 = new User();
user1.setUsername("lisi");
user1.setPassword("");
userList.add(user1);
String json = gson.toJson(userList);
pw.print(json);
}

android通过HttpClient与服务器JSON交互的更多相关文章

  1. Android 客户端和服务器 json交互

    http://www.cnblogs.com/jyan/articles/2544974.html 1.JSON(JavaScript Object Notation) 是一种轻量级的数据交换格式. ...

  2. android get或post及HttpClient与服务器数据交互

    1.Service package mydemo.mycom.demo2.service; import org.apache.http.HttpResponse; import org.apache ...

  3. Android实现与PHP服务器的交互

    今天算是有点小激动呢!拿到Android与PHP这个课题已经两个星期了,直到今天才算是有了一点点小收获. 虽然还是没能成功上传到服务器,不过已经看到了曙光,已经实现了一半了,那就是已经连接到了服务器. ...

  4. android通过httpClient请求获取JSON数据并且解析

    使用.net创建一个ashx文件,并response.write  json格式 public void ProcessRequest(HttpContext context) { context.R ...

  5. Android使用HttpClient向服务器传输文件

    HttpClient是Apache Jakarta Common下的子项目,可以用来提供功能丰富的支持HTTP协议的客户端编程工具包,这几天写客户端的时候遇到个问题,“客户端需要向服务器发送Post请 ...

  6. Android使用HttpClient请求服务器代码优化版

    首先,我在前面的两篇博文中介绍了在Android中,除了使用java.net包下HttpUrlConnection的API访问HTTP服务之外,我们还可以换一种途径去完成工作.Android SDK附 ...

  7. Android使用HttpClient以Post、Get请求服务器发送数据的方式(普通和json)

    讲这个之前,我们先来说说get和post两种请求的区别吧!!! 1. GET提交的数据会放在URL之后,以?分割URL和传输数据,参数之间以&相连,如EditPosts.jsp?name=te ...

  8. 使用基于Android网络通信的OkHttp库实现Get和Post方式简单操作服务器JSON格式数据

     目录 前言 1 Get方式和Post方式接口说明 2 OkHttp库简单介绍及环境配置 3 具体实现 前言 本文具体实现思路和大部分代码参考自<第一行代码>第2版,作者:郭霖:但是文中讲 ...

  9. unity用json和服务器数据交互

    第一种类型:服务器json数据是个对象 /// <summary> /// 获取用户信息初始化信息 /// </summary> void InitUserMessage() ...

随机推荐

  1. Java Debug调试简单方法--static使用

    Public class Debug { public Debug() { } static void debugPrint(String src) { //System.out.print(src) ...

  2. Maven应用

    Maven进行项目管理很方便,下面介绍一下学习maven中的笔记.我是在Windows上运行的          有些知识点没有试,只是收集转载,很可能存在错误 1.安装 解压缩之后,配置环境变量MA ...

  3. [转]使用Gradle发布Android开源项目到JCenter

      转自:http://blog.csdn.net/maosidiaoxian/article/details/43148643 使用Gradle发布Android开源项目到JCenter 分类: G ...

  4. wireless tool 移植

    在linux上调试wifi, 需要移植wireless tool进行验证,本文记录移植方法. 参考链接 http://www.cnblogs.com/zengjfgit/p/5601473.html ...

  5. Performance Analyzer Tool

    PAL工具的使用大同小异,网上看到这篇文章挺不错的,直接翻译过来.如果你在过去有Exchange性能问题,你肯定知道有很多可变因素会影响Exchange整体性能,有时需要很长的时间才能找到问题的根源, ...

  6. HTML5 Canvas绘文本动画(使用CSS自定义字体)

    一.HTML代码: <!DOCTYPE html> <html> <head> <title>Matrix Text - HTML5 Canvas De ...

  7. C#异步:实现一个最简单的异步

    异步就是方法异步执行, 这个好理解. 异步有啥用? 以前只是听说过, 也不想计较. 不过还是碰到了需要这个东西的时候. 比如: 定时执行, 如果不用异步方法,也不用定时器,只用Thread.Sleep ...

  8. angular懒加载的一些坑

    写在前面 最近在工作中接触到angular模块化打包加载的一些内容,感觉中间踩了一些坑,在此标记一下. 项目背景: 项目主要用到angularJs作为前端框架,项目之前发布的时候会把所有的前端脚本打包 ...

  9. html5,实例开发代码

    <!DOCTYPE html><html lang="en"><head>    <meta charset="UTF-8&qu ...

  10. php调用一个c语言写的接口问题

    用php调用一个c语言写的soap接口时,遇到一个问题:不管提交的数据正确与否,都无法请求到接口 1.用php标准的soap接口去请求 2.拼接xml数据去请求 以上两种方式都不正确 解决办法:php ...