Android 手机端与服务端POST数据交互类

package com.wizzer.tools;

import java.io.*;
import java.net.URLEncoder;

import java.util.*;

import org.apache.http.HttpResponse;

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;
import org.apache.http.NameValuePair;
import org.json.JSONArray;
import org.json.JSONException;

import android.app.Activity;
import android.app.Dialog;
import android.app.ProgressDialog;

public class BaseProtocol
{
private StringBuilder sb = new StringBuilder();
private HttpClient httpClient;
private HttpPost httpRequest;
private HttpResponse response;
private List<NameValuePair> nameValuePair = new ArrayList<NameValuePair>();
private static final int DIALOG1_KEY = 0;
private static final int DIALOG2_KEY = 1;

public BaseProtocol()
{
httpClient = new DefaultHttpClient();
}

/**
* *向服务器端发送请求 * *@paramurl *@throwsException
*
* @throws UnsupportedEncodingException
*/
public void pack(String url) throws Exception
{
httpClient = new DefaultHttpClient();
httpRequest = new HttpPost(url);
httpRequest.setEntity(new UrlEncodedFormEntity(nameValuePair));
response = httpClient.execute(httpRequest);
}

/** *得到返回数据 * *@paramurl *@return *@throwsException */

public String parse() throws Exception
{
// TODO状态处理500200
if (response.getStatusLine().getStatusCode() == 200)
{
BufferedReader bufferedReader2 = new BufferedReader(new InputStreamReader(response.getEntity().getContent()));
for (String s = bufferedReader2.readLine(); s != null; s = bufferedReader2.readLine())
{
sb.append(s);
}
}
return sb.toString();
}

/***
* 向服务器发送信息 * *@paramkey *@paramvalue
*
* @throws UnsupportedEncodingException
*/
public void addNameValuePair(String key, String value) throws UnsupportedEncodingException
{
nameValuePair.add(new BasicNameValuePair(key, URLEncoder.encode(value, HTTP.UTF_8)));
}

/** *返回JSONArray对象数据模型 * *@return *@throwsJSONException */

public JSONArray getJSON() throws JSONException
{
return new JSONArray(sb.toString());
}

}

你可能感兴趣的:(apache,android,json,.net)