Java发送http请求,参数形式为json
不介绍知识,哪不懂自己搜。只记录平时用到的,可以给其他人做参考。
需要传递的参数为json形式,比如手机号{“phone”:“123456”}
public static int sendPost(String mobile,int user_id){
URL postURL = null;
HttpURLConnection httpUrl = null;
String url = "这里换成你需要访问的地址";
String info = "{\"phone\":\""+mobile+"\"}";;
try {
postURL = new URL(url);
httpUrl = (HttpURLConnection) postURL.openConnection();
httpUrl.setDoInput(true);
httpUrl.setDoOutput(true);
httpUrl.setUseCaches(false);
httpUrl.setRequestProperty("Content-Type", "application/json;chartset=UTF-8");
httpUrl.setRequestProperty("Cache-Control", "");
httpUrl.setRequestProperty("User-Agent", "");
httpUrl.setRequestProperty("Accept", "");
httpUrl.setRequestProperty("Pragma", "");
httpUrl.setRequestMethod("POST");
OutputStreamWriter owwriter = new OutputStreamWriter(httpUrl.getOutputStream(),"utf-8");
owwriter.append(info);
owwriter.flush();
owwriter.close();
if (httpUrl.getResponseCode() == 200) {
InputStream inputStr = httpUrl.getInputStream();
byte[] b = new byte[inputStr.available()];
inputStr.read(b);
JSONObject jsonObject=JSONObject.fromObject(new String(b));
(实体类名) bean = (efftiveBean)JSONObject.toBean(jsonObject, 实体类名.class);
inputStr.close();
} else {
logger.info("调用服务返回码为"+httpUrl.getResponseCode());
logger.info("调用失败,不做优化");
}
} catch (Exception e) {
e.printStackTrace();
logger.info(e.toString());
logger.info("调用服务异常 不做优化]");
}
return result;
}
}
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)