一个方法
下面展示一些 内联代码片
。
// 传入json报文 调用接口 返回json响应报文
private String httpURLPOSTCases( JSONObject jsonAllMsg ) {
String methodUrl = mUrl;
HttpURLConnection connection = null;
BufferedReader reader = null;
String line = null;
StringBuilder result = new StringBuilder();
try {
URL url = new URL(methodUrl);
System.out.println("---vvip---url:"+url);
connection = (HttpURLConnection) url.openConnection();// 根据URL生成HttpURLConnection
connection.setDoOutput(true);// 设置是否向connection输出,因为这个是post请求,参数要放在http正文内,因此需要设为true,默认情况下是false
connection.setDoInput(true); // 设置是否从connection读入,默认情况下是true;
connection.setRequestMethod("POST");// 设置请求方式为post,默认GET请求
connection.setUseCaches(false);// post请求不能使用缓存设为false
connection.setInstanceFollowRedirects(true);// 设置该HttpURLConnection实例是否自动执行重定向
connection.setRequestProperty("Accept", "application/json");// 设置接收数据的格式
connection.setRequestProperty("Content-Type", "application/json");
connection.connect();// 建立TCP连接,getOutputStream会隐含的进行connect,所以此处可以不要
OutputStreamWriter dataout = new OutputStreamWriter(connection.getOutputStream(),"UTF-8");// utf-8编码
dataout.append(jsonAllMsg.toString());
dataout.flush();
dataout.close();
System.out.println("---vip---ResponseCode:"+connection.getResponseCode());
int responseCode = connection.getResponseCode();
if(!"200".equals(""+responseCode)){
this.buildError("httpURLPOSTCases", "接口没调通");
System.out.println("接口没调通");
}
if (connection.getResponseCode() == HttpURLConnection.HTTP_OK) {
reader = new BufferedReader(new InputStreamReader(connection.getInputStream(), "UTF-8"));// 发送http请求
while ((line = reader.readLine()) != null) {
result.append(line);//
}
}
}catch(Exception e){
e.printStackTrace();
this.buildError("httpURLPOSTCase", e.getMessage());
}
return result.toString();
}