jackson简介
ObjectMapper:把自定义的Java类,或者一个Jackson指定的树形结构生成为JSON文件。
Jackson的在线API文档可以在http://wiki.fasterxml.com/JacksonInFiveMinutes中找到。
Jackson依赖包:
>jackson-core-2.2.3.jar
jackson-annotations-2.2.3.jar
jackson-databind-2.2.3.jar
Httpclient简介:
2.1 HttpClient是Apache Jakarta Common下的子项目,用来提供高效的、最新的、
功能丰富的支持HTTP协议的客户端编程工具包,并且它支持HTTP协议最新的版本和协议。
2.2 Android已成功集成了HttpClient,这意味这开发人员可以直接在Android应用中使用
HtppClient来提交请求、接收响应
注:在API 23中,Google已经移除了移除了Apache HttpClient相关的类 ,
在build.gradle中的android {}中加上useLibrary 'org.apache.http.legacy',
HttpClient的使用步骤
3.1 创建HttpClient对象
HttpClient httpClient = new DefaultHttpClient();
3.2 创建HttpGet(或HttpPost)对象
HttpGet HttpGet = new HttpGet(“http://www.baidu.com“);
HttpPost httpPost = new HttpPost(“http://www.baidu.com“);
3.3 添加参数(可选)(setParams()/params.add())
setParams(HttpParams params)//HttpGet和HttpPost共有
setEntity(HttpEntity entity)//HttpPost独有
List params = new ArrayList();
params.add(new BasicNameValuePair(“age”, “20”));
params.add(new BasicNameValuePair(“newsCategoryId”, “1”));
HttpEntity paramEntity = new UrlEncodedFormEntity(params,”UTF-8”);
httpPost.setEntity(paramEntity);
3.4 发送GET(或POST)请求,并获得响应
HttpResponse httpResponse = httpClient.execute(HttpUriRequest request);
注1:HttpUriRequest为HttpGet和HttpPost的父类
注2:需要添加允许网络访问权限,不然会报错“java.lang.SecurityException: Permission denied (missing INTERNET permission?)”
<uses-permission android:name="android.permission.INTERNET" />
注3:如果地址错误,或服务器未开户,HttpClient这SB会等待N久(>24小时)。
所以请记得设置超时时间,所以请记得设置超时时间,所以请记得设置超时时间。
另外HttpClient版本不一样,代码也不一样。下面的4.0版本的写法
httpClient.getParams().setParameter(CoreConnectionPNames.CONNECTION_TIMEOUT, 2000);// 连接时间
httpClient.getParams().setParameter(CoreConnectionPNames.SO_TIMEOUT, 2000);// 数据传输时间
3.5 处理响应
3.5.1 响应状态码(200)
httpResponse.getStatusLine().getStatusCode()
3.5.2 响应头
getAllHeaders()/getHeaders(String name)
3.5.3 响应内容
HttpEntity httpEntity = httpResponse.getEntity();//此对象包含服务器的响应内容
String result = EntityUtils.toString(httpEntity);
注:
连接真机时:
关于org.apache.http.conn.HttpHostConnectException: Connection to
refused错误的解决办法
增加网络访问权限:
找到 AndroidManifest.xml 文件。在application标签后面加上
检查ip地址:
启动的android模拟器吧自己也当成127.0.0.1和localhost,如果使用了localhost或者127.0.0.1则会被拒绝访问,
把ip地址改成实际地址,如:192.168.1.5
Android和java连接时一定在联网的状态下,并且在同一局域网
Android里导jar包:
1.把Android切换成project
2.把jar包复制到project里的libs
3.选中复制的jar包,右键选择Add As Library
案例一
连接eclipse实现增删查改(run输出):
HttpClientPost代码:
package com.example.t212_a10;
import java.io.Serializable;
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.HttpPost;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.message.BasicNameValuePair;
import org.apache.http.params.CoreConnectionPNames;
import org.apache.http.util.EntityUtils;
import android.os.AsyncTask;
public class HttpClientPost implements Serializable {
private static final long serialVersionUID = 1777547416049652217L;
private static HttpClient httpClient = new DefaultHttpClient();
static {
httpClient.getParams().setParameter(
CoreConnectionPNames.CONNECTION_TIMEOUT, 2000);// 连接时间
httpClient.getParams().setParameter(CoreConnectionPNames.SO_TIMEOUT,
3000);// 数据传输时间
}
// 字符集
private static String encoding = "UTF-8";
// 服务器地址+端口号+项目名
private static String basePath = "http://192.168.43.226:8080/JQUERY2";
// 子控制器的路径
private String path;
// 保存请求中的参数
private List<NameValuePair> params = new ArrayList<NameValuePair>();;
public HttpClientPost(String path) {
super();
this.path = path;
}
/**
* 向POST请求中添加参数
*
* @param name
* @param value
*/
public void addParam(String name, String value) {
if (value == null) {
params.add(new BasicNameValuePair(name, ""));
} else {
params.add(new BasicNameValuePair(name, value));
}
}
/**
* 提交POST请求
*/
@SuppressWarnings("unchecked")
public void submit(final HttpClientPost.Callback callback) {
new AsyncTask() {
private String json;
@Override
protected Object doInBackground(Object... args) {
try {
// 1. 创建HttpClient对象
// 2. 创建HttpGet(或HttpPost)对象
HttpPost httpPost = new HttpPost(basePath + path);
// 3. 向POST请求中添加参数(可选)
if (0 != params.size()) {
HttpEntity paramEntity = new UrlEncodedFormEntity(
params, encoding);
httpPost.setEntity(paramEntity);
}
// 4. 发送POST请求,并获得响应
HttpResponse httpResponse = httpClient.execute(httpPost);
// 5. 处理响应
if (200 == httpResponse.getStatusLine().getStatusCode()) {
HttpEntity responseEntity = httpResponse.getEntity();// 此对象包含服务器的响应内容
this.json = EntityUtils.toString(responseEntity);
}
} catch (Exception e) {
throw new RuntimeException(e);
}
return null;
}
protected void onPostExecute(Object result) {
callback.execute(this.json);
}
}.execute();
}
public static interface Callback {
void execute(String json);
}
}
xml代码:
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical"
tools:context=".MainActivity">
<Button
android:id="@+id/bt_main_add"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:text="新增" />
<Button
android:id="@+id/bt_main_edit"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:text="修改" />
<Button
android:id="@+id/bt_main_del"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:text="删除" />
<Button
android:id="@+id/bt_main_load"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:text="查单个" />
<Button
android:id="@+id/bt_main_list"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:text="查全部" />
</LinearLayout>
java代码:
package com.example.t212_a10;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.widget.Button;
import com.fasterxml.jackson.databind.ObjectMapper;
import java.io.IOException;
import java.util.Map;
public class MainActivity extends AppCompatActivity implements View.OnClickListener {
private Button bt_main_add; //增
private Button bt_main_edit; //修
private Button bt_main_del; //删
private Button bt_main_load; //单个查
private Button bt_main_list; //查所有
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
//查找控件
findViews();
//绑定监听器
bt_main_add.setOnClickListener(this);
bt_main_edit.setOnClickListener(this);
bt_main_del.setOnClickListener(this);
bt_main_load.setOnClickListener(this);
bt_main_list.setOnClickListener(this);
}
private void findViews() {
bt_main_add = (Button) findViewById(R.id.bt_main_add);
bt_main_edit = (Button) findViewById(R.id.bt_main_edit);
bt_main_del = (Button) findViewById(R.id.bt_main_del);
bt_main_load = (Button) findViewById(R.id.bt_main_load);
bt_main_list = (Button) findViewById(R.id.bt_main_list);
}
@Override
public void onClick(View v) {
switch (v.getId()) {
case R.id.bt_main_add:
add();
break;
case R.id.bt_main_edit:
edit();
break;
case R.id.bt_main_del:
del();
break;
case R.id.bt_main_load:
load();
break;
case R.id.bt_main_list:
list();
break;
}
}
private void add() {
Log.i("test", "add...");
HttpClientPost post=new HttpClientPost("/jsp/userAction.action");
post.addParam("method","userAdd");
post.addParam("SerialNo","11");
post.addParam("uid","0011");
post.addParam("uname","bbbb");
post.addParam("upwd","123456");
post.submit(new HttpClientPost.Callback() {
@Override
public void execute(String json) {
Log.i("server44:",json);
}
});
}
private void edit() {
Log.i("test", "edit...");
HttpClientPost post=new HttpClientPost("/jsp/userAction.action");
post.addParam("method","userUpdate");
post.addParam("SerialNo","1");
post.addParam("uid","001");
post.addParam("uname","张三aaa");
post.addParam("upwd","123456");
post.submit(new HttpClientPost.Callback() {
@Override
public void execute(String json) {
Log.i("server22:",json);
}
});
}
private void del() {
Log.i("test", "del...");
HttpClientPost post=new HttpClientPost("/jsp/userAction.action");
post.addParam("method","userDelete");
post.addParam("SerialNo","2");
post.submit(new HttpClientPost.Callback() {
@Override
public void execute(String json) {
Log.i("server66:",json);
}
});
}
private void load() {
Log.i("test", "load...");
HttpClientPost post=new HttpClientPost("/jsp/userAction.action");
post.addParam("method","userList");
post.addParam("uname","李四");
post.submit(new HttpClientPost.Callback() {
@Override
public void execute(String json) {
Log.i("server",json);
ObjectMapper om=new ObjectMapper();
try {
Map map = om.readValue(json, Map.class);
Log.i("server",map.get("total").toString());
Log.i("server",map.get("rows").getClass().getName());
} catch (IOException e) {
e.printStackTrace();
}
}
});
}
private void list() {
Log.i("test", "list...");
}
}