因为项目需求,目前开发的android应用需要使用json与php服务端进行通信,通过get,post方式与服务器端进行数据交互,基本实现方式记录如下:

Get方式:

protected String getRequest(String url, DefaultHttpClient client) throws Exception {

DefaultHttpClient client = new DefaultHttpClient(new BasicHttpParams());

//超时请求

client.getParams().setParameter(CoreConnectionPNames.CONNECTION_TIMEOUT, 5000);

//读取超时

client.getParams().setParameter(CoreConnectionPNames.SO_TIMEOUT, 5000);

String result = null;

int statusCode = 0;

HttpGet getMethod = new HttpGet(url);

try {

HttpResponse httpResponse = client.execute(getMethod);

//statusCode == 200 正常

statusCode = httpResponse.getStatusLine().getStatusCode();

//处理返回的httpResponse信息

result = retrieveInputStream(httpResponse.getEntity());

} catch (Exception e) {

} finally {

getMethod.abort();

}

return result;

}

/**

* 处理httpResponse信息,返回String

*

* @param httpEntity

* @return String

*/

protected String retrieveInputStream(HttpEntity httpEntity) {

Long l = httpEntity.getContentLength();

int length = (int) httpEntity.getContentLength();

//the number of bytes of the content, or a negative number if unknown. If the content length is known but exceeds Long.MAX_VALUE, a

negative number is returned.

//length==-1,下面这句报错,println needs a message

//System.out.println(“length = “+length);

if (length < 0) length = 10000; StringBuffer stringBuffer = new StringBuffer(length); try { InputStreamReader inputStreamReader = new InputStreamReader(httpEntity.getContent(), HTTP.UTF_8); char buffer[] = new char[length]; int count; while ((count = inputStreamReader.read(buffer, 0, length – 1)) > 0) {

stringBuffer.append(buffer, 0, count);

}

}catch(IOException e){

e.printStackTrace();

}

return stringBuffer.toString();

}

Post方式:

List nameValuePairs = new List();//构建post给php的参数

nameValuePairs.add(new BasicNameValuePair(“key”,”value”));

//通过post获得数据

public static String postHttpData(String url,List nameValuePairs)

{

String resultStr=null;

HttpClient httpclient = new DefaultHttpClient();

//超时请求

httpclient.getParams().setParameter(CoreConnectionPNames.CONNECTION_TIMEOUT, 5000);

//读取超时

httpclient.getParams().setParameter(CoreConnectionPNames.SO_TIMEOUT, 5000);

HttpPost httppost = new HttpPost(url);

try {

httppost.setEntity(new UrlEncodedFormEntity(nameValuePairs));

HttpResponse response;

response=httpclient.execute(httppost);

resultStr=retrieveInputStream(httpResponse.getEntity());

} catch (UnsupportedEncodingException e) {

Log.d(url, “UnsupportedEncodingException”);

e.printStackTrace();

} catch (ClientProtocolException e) {

Log.d(url, “ClientProtocolException”);

e.printStackTrace();

} catch (IOException e) {

Log.d(url, “IOException”);

e.printStackTrace();

}

return resultStr;

}

在使用过程中,可以从安全性和长度大小等方面根据需求进行选择。