eclipse 连接 Android 获取数据库数据

package com.example.t211_05;

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.43.171:8089/Shu_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);
	}
}

//注意获取本机的端口号,不要使用localhost
在这里插入图片描述

猜你喜欢

转载自blog.csdn.net/zimuliusu/article/details/82781729
今日推荐