1.新建.properties文件,在文件里写要请求的url地址: URL= 地址;
2.读取.properties文件
ResourceBundle rb = ResourceBundle.getBundle() // 括号里面写properties文件的路径
3.读取url地址
rb.getString("URL")
4.post发生数据
下面是一个post发送json数据的工具类
public class HttpUtils {
private static final StringCHARSET ="UTF-8";
private static HttpClienthttpClient =null;
/**
* post请求
* @param url url地址
* @param jsonParam 参数
* @param noNeedResponse 不需要返回结果
* @return
*/
public static String httpPost(String url, JSONObject jsonParam,boolean noNeedResponse){
//post请求返回结果
String jsonResult ="";
try {
httpClient = HttpClients.createDefault();
HttpPost method =new HttpPost(url);
if (null != jsonParam) {
//解决中文乱码问题
StringEntity entity =new StringEntity(jsonParam.toString(),"utf-8");
entity.setContentEncoding("UTF-8");
entity.setContentType("application/json");
method.setEntity(entity);
}
HttpResponse result =httpClient.execute(method);
url = URLDecoder.decode(url,"UTF-8");
System.out.println(url);
/**请求发送成功,并得到响应**/
if (result.getStatusLine().getStatusCode() ==200) {
String str ="";
try {
/**读取服务器返回过来的json字符串数据**/
str = EntityUtils.toString(result.getEntity());
if (noNeedResponse) {
return null;
}
/**把json字符串转换成json对象**/
jsonResult = str;
}catch (Exception e) {
e.printStackTrace();
}
}
}catch (Exception e) {
e.printStackTrace();
}
return jsonResult;
}
}