java接口返回值_java后台调用接口并返回值

import java.io.BufferedReader;

import java.io.DataOutputStream;

import java.io.IOException;

import java.io.InputStreamReader;

import java.net.HttpURLConnection;

import java.net.URL;

import java.net.URLEncoder;

public class HttpOrderUtil {

// 接口

private static final String post_url = "接口的地址";

public static String httpURLConnectionPOST(需要传的参数) {

StringBuilder sb = new StringBuilder();

try {

URL url = new URL(post_url);//把字符串转换为URL请求地址

HttpURLConnection connection = (HttpURLConnection) url

.openConnection();//此时cnnection只是为一个连接对象,待连接中

connection.setConnectTimeout(5 * 1000);//设置连接超时时间为5秒

connection.setReadTimeout(20 * 1000);//设置读取超时时间为20秒

connection.setDoOutput(true);//设置连接输出流为true,默认false

connection.setDoInput(true);//设置连接输入流为true

connection.setRequestMethod("POST");//设置请求方式为post

connection.setUseCaches(false);// post请求缓存设为false

connection.setInstanceFollowRedirects(true);//设置该HttpURLConnection实例是否自动执行重定向

connection.setRequestProperty("Content-Type",

"application/x-www-form-urlencoded;charset=utf-8");//请求的content-type为application/x-www-form-urlencoded;

//charset=UTF-8

connection.connect();//建立连接

DataOutputStream dataout = new DataOutputStream(

connection.getOutputStream());//创建输入输出流,用于往连接里面输出携带的参数

String 参数= "参数="

+ URLEncoder.encode(需要传的参数, "utf-8");

dataout.writeBytes(参数);

dataout.flush();//输出完成后刷新并关闭流

dataout.close();

//System.out.println(connection.getResponseCode());

// 如果请求响应码是200,则表示成功

if (connection.getResponseCode() == 200) {

BufferedReader bf = new BufferedReader(new InputStreamReader(

connection.getInputStream(), "UTF-8"));

String line;

while ((line = bf.readLine()) != null) {

sb.append(line);

}

bf.close();

}

connection.disconnect();//断开连接

} catch (IOException e) {

e.printStackTrace();

}

return sb.toString();

}

}

  • 0
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值