今天项目接口一直调不通,于是我修改了相关的代码
在网上找到了一个很好的例子:
public static String httpPost(String urlStr,Map<String,String> params){
URL connect;
StringBuffer data = new StringBuffer();
try {
connect = new URL(urlStr);
HttpURLConnection connection = (HttpURLConnection)connect.openConnection();
connection.setRequestMethod("POST");
connection.setDoOutput(true);
connection.setDoInput(true);
connection.setUseCaches(false);//post不能使用缓存
connection.setInstanceFollowRedirects(true);
connection.setRequestProperty("accept", "*/*");
connection.setRequestProperty("connection", "Keep-Alive");
connection.setRequestProperty("user-agent", "Mozilla/4.0 (compatible; MSIE 6.0; Windows NT 5.1;SV1)");
OutputStreamWriter paramout = new OutputStreamWriter(
connection.getOutputStream(),"UTF-8");
String paramsStr = ""; //拼接Post 请求的参数
for(String param : params.keySet()){
paramsStr += "&" + param + "=" + params.get(param);
}
if(!paramsStr.isEmpty()){
paramsStr = paramsStr.substring(1);
}
paramout.write(paramsStr);
paramout.flush();
BufferedReader reader = new BufferedReader(new InputStreamReader(
connection.getInputStream(), "UTF-8"));
String line;
while ((line = reader.readLine()) != null) {
data.append(line);
}
paramout.close();
reader.close();
} catch (Exception e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
return data.toString();
}
public static void main(String[] args) {
JSONObject json1=new JSONObject();
json1.put("DTYPE",'0');
json1.put("KEY", "jsddkj");
json1.put("CODE","FacilityServer.getFacilityList");
JSONObject json2=new JSONObject();
json2.put("table", "navi_jiayouzhan");
json2.put("x1","118.181837");
json2.put("y1","33.557312");
json2.put("x2","119.254133");
json2.put("y2","34.631957");
json1.put("DATA",json2);
Map<String, String> map=new HashMap<>();
map.put("DATA", json1.toString());
String url="";
System.out.println(httpPost(url,map));
}
下面的参数仅仅我是本地需要的参数,希望对你有所帮助
希望大家一起学习交流: