http协议get方法请求:
/**
* 请求数据 Get方法请求参数
* @param values 参数
* @param url
* @return 返回值
*/
@SuppressWarnings({ "resource", "deprecation" })
public static JSONObject doGet(List<BasicNameValuePair> values, String url) {
HttpClient client = new DefaultHttpClient();//申明一个网络访问客户端
String tmpUrl = url + "?" + values.get(0);
HttpGet httpget = new HttpGet(tmpUrl);//post方式
String resp = null;
JSONObject jsStr = null;
try {
HttpResponse response = client.execute(httpget);//响应结果
HttpEntity resEntity = response.getEntity();
if (resEntity != null) {
resp = EntityUtils.toString(resEntity);
jsStr = JSONObject.fromObject(resp);
EntityUtils.consume(resEntity);
}
} catch (UnsupportedEncodingException e) {
e.printStackTrace();
} catch (ClientProtocolException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
} finally {
client.getConnectionManager().shutdown();
}
return jsStr;
}
http协议post方法请求:
/**
* 请求数据
* @param values 参数
* @param url
* @return 返回值
*/
@SuppressWarnings({ "resource", "deprecation" })
public static JSONObject doPost(List<BasicNameValuePair> values, String url) {
HttpClient client = new DefaultHttpClient();
HttpPost httppost = new HttpPost(url);
String resp = null;
JSONObject jsStr = null;
try {
httppost.setEntity(new UrlEncodedFormEntity(values, HTTP.UTF_8));
HttpResponse response = client.execute(httppost);
HttpEntity resEntity = response.getEntity();
if (resEntity != null) {
resp = EntityUtils.toString(resEntity, "UTF-8");
System.out.println(resp);
jsStr = JSONObject.fromObject(resp);
EntityUtils.consume(resEntity);
}
} catch (UnsupportedEncodingException e) {
e.printStackTrace();
} catch (ClientProtocolException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
} finally {
client.getConnectionManager().shutdown();
}
return jsStr;
}
其中:
List<BasicNameValuePair> values = new ArrayList<BasicNameValuePair>();
try {
values.add(new BasicNameValuePair("param", data));//param参数名称,data为发送数据
} catch (UnsupportedEncodingException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
//发送信息,接收回复
JSONObject jsonData = doPost(values, CodeConsts.COUPONS_CONFIRM_URL);//CodeConsts.COUPONS_CONFIRM_URL为url常量