Android httpclient、json
webservice->xml
jackson->json
从第三方项目中拿数据通常有两种方式(根据数据交互的格式来定)
xml->webservice/httpClient
json->httpClient
java java
java android
java ios
java 微信
-
jackson
1.1 Java->Json
1.1.1 ObjectMap
1.1.2 JsonGenerator
1.1.3 @JsonIgnore
hibernate中一对多、多对多双向关联会出现这种死循环 -
简介
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的作用是在后台模拟,浏览访问后台代码的操作
案例一:HttpClient的使用步骤 -
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(HttpParams params)//HttpGet和HttpPost共有
setEntity(HttpEntity entity)//HttpPost独有
List<NameValuePair> params = new ArrayList<NameValuePair>();
params.add(new BasicNameValuePair("age", "20"));
params.add(new BasicNameValuePair("like", "aa"));
params.add(new BasicNameValuePair("like", "bb"));
params.add(new BasicNameValuePair("like", "cc"));
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);
//代码展示 工具类
package com.example.myapplication08;
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;
/**
- 封装 HttpClient对象POST请求
*/
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.7.111:8080/web_easyUI";
// 子控制器的路径
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);
}
}
// 代码展示, 增删改查实现类、只写了查询
package com.example.myapplication08;
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.List;
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...");
}
private void edit() {
Log.i("test", "edit...");
}
private void del() {
Log.i("test", "del...");
}
private void load() {
Log.i("test", "load...");
}
private void list() {
Log.i("test", "list...");
HttpClientPost clientPost = new HttpClientPost("/userAction.action");
clientPost.addParam("methodName","listUser");
clientPost.submit(new HttpClientPost.Callback() {
@Override
public void execute(String json) {
Log.i("json",json);
ObjectMapper om = new ObjectMapper();
try {
Map map = om.readValue(json, Map.class);
List rows = (List) map.get("rows");
Map<String,String> o = (Map<String, String>) rows.get(0);
Log.i("uname",o.get("uname"));
} catch (IOException e) {
e.printStackTrace();
}
}
});
}
}
// 代码展示 xml框
<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="查全部" />
案例二:使用HttpClientUtils与服务器通信
4. Android客户端与服务器通信
4.1 JSON数据交换
android系统内置了对象json的支持,另外json其实就以下几个对象的使用:
JSONObject、JSONArray、JSONStringer、JSONException
4.2 web service,底层使用xml交换数据
- 关于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即时通讯demo开源(android studio实现聊天功能)
-
Vue中android4.4不兼容问题的解决方法
-
JS 无限级 Select效果实现代码(json格式)
-
string转jsonarray有双引号(Java把string转json格式的办法)
-
Android获取本地相册图片和拍照获取图片的实现方法
-
Android中Okhttp3实现上传多张图片同时传递参数
-
C#简单快速的json组件fastJSON使用介绍
-
Android自定义View简易折线图控件(二)
-
Android编程中延后处理事件的方法小结
-
Android自定义ScrollView实现放大回弹效果实例代码