以下方法支持http和https的请求
public static JSONObject httpPost(String url, String data,String token){
//post请求返回结果
DefaultHttpClient httpClient = new DefaultHttpClient();
JSONObject jsonResult = null;
HttpPost method = new HttpPost(url);
System.out.println("------------------"+url);
try {
if (null != data) {
//解决中文乱码问题
StringEntity entity = new StringEntity(data, "utf-8");
entity.setContentEncoding("UTF-8");
entity.setContentType("application/json");
method.setEntity(entity);
method.setHeader("Authorization",token);
}
HttpResponse result = httpClient.execute(method);
url = URLDecoder.decode(url, "UTF-8");
/**请求发送成功,并得到响应**/
if (result.getStatusLine().getStatusCode() == 200) {
System.out.println("----------请求成功-------------------");
String str;
try {
/**读取服务器返回过来的json字符串数据**/
str = EntityUtils.toString(result.getEntity());
System.out.println(str);
} catch (Exception e) {
System.out.println("请求失败");
}
}else{
System.out.println("----------请求失败---------------");
System.out.println(EntityUtils.toString(result.getEntity()));
}
} catch (IOException e) {
e.printStackTrace();
System.out.println("请求失败");
}
return jsonResult;
}