android通过HttpClient与服务器JSON交互
通过昨天对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交互的更多相关文章
- Android 客户端和服务器 json交互
http://www.cnblogs.com/jyan/articles/2544974.html 1.JSON(JavaScript Object Notation) 是一种轻量级的数据交换格式. ...
- android get或post及HttpClient与服务器数据交互
1.Service package mydemo.mycom.demo2.service; import org.apache.http.HttpResponse; import org.apache ...
- Android实现与PHP服务器的交互
今天算是有点小激动呢!拿到Android与PHP这个课题已经两个星期了,直到今天才算是有了一点点小收获. 虽然还是没能成功上传到服务器,不过已经看到了曙光,已经实现了一半了,那就是已经连接到了服务器. ...
- android通过httpClient请求获取JSON数据并且解析
使用.net创建一个ashx文件,并response.write json格式 public void ProcessRequest(HttpContext context) { context.R ...
- Android使用HttpClient向服务器传输文件
HttpClient是Apache Jakarta Common下的子项目,可以用来提供功能丰富的支持HTTP协议的客户端编程工具包,这几天写客户端的时候遇到个问题,“客户端需要向服务器发送Post请 ...
- Android使用HttpClient请求服务器代码优化版
首先,我在前面的两篇博文中介绍了在Android中,除了使用java.net包下HttpUrlConnection的API访问HTTP服务之外,我们还可以换一种途径去完成工作.Android SDK附 ...
- Android使用HttpClient以Post、Get请求服务器发送数据的方式(普通和json)
讲这个之前,我们先来说说get和post两种请求的区别吧!!! 1. GET提交的数据会放在URL之后,以?分割URL和传输数据,参数之间以&相连,如EditPosts.jsp?name=te ...
- 使用基于Android网络通信的OkHttp库实现Get和Post方式简单操作服务器JSON格式数据
目录 前言 1 Get方式和Post方式接口说明 2 OkHttp库简单介绍及环境配置 3 具体实现 前言 本文具体实现思路和大部分代码参考自<第一行代码>第2版,作者:郭霖:但是文中讲 ...
- unity用json和服务器数据交互
第一种类型:服务器json数据是个对象 /// <summary> /// 获取用户信息初始化信息 /// </summary> void InitUserMessage() ...
随机推荐
- The index also can be used for LIKE comparisons if the argument to LIKE is a constant string that does not start with a wildcard character.
http://dev.mysql.com/doc/refman/5.7/en/index-btree-hash.html MySQL 5.7 Reference Manual / ... / ...
- butterknife异常提示:attribute value must be constant
就是因为你的android工程是lib类型的 如: apply plugin: 'com.android.library' android { compileSdkVersion 23 buildTo ...
- 在block中使用self
__weak typeof(self) weakSelf = self; [self doABlockOperation:^{ __strong typeof(weakSelf) strong ...
- 如何使用Sitemap和menu创建网站导航
1.添加Sitemap文件 将Sitemap内容替换为如下示例代码: <?xml version="1.0" encoding="utf-8" ?> ...
- 求文件的m至n行
#!/usr/bin/env python def read_file(file_name,start,stop): start_line = 0 try: with open(file_name) ...
- MVC中的模型
为MVC Music Store 建模 建模代码: public class Album { public virtual int AlbumId { get; set; } public virtu ...
- Jmeter中察看结果树中的响应数据,中文显示乱码问题处理
打开apache-jmeter-xxx\bin\jmeter.properties文件,搜索"encoding"关键字,找到如下配置: # The encoding to be u ...
- RelativeLayout实现左中右布局
<RelativeLayout android:layout_width="match_parent" android:layout_height="wrap_co ...
- ECMAScript数据类型
[ 基本数据类型 ]-->5种 Undefined Null Boolean Number String [ 复杂数据类型 ]-->1种 Object [ typeof 返回值] --&g ...
- BJFU 1057
描述 斐波那契额数列,我们都知道.现在qingyezhu想求斐波那契的某项值对2的某次方的结果.你可以帮一下他吗?他好可怜哦!计算了N的N次方次都错了,也挨了ben大哥的N的N次方次的训了.我想你是个 ...