java以json格式向后台服务器接口发送请求的实例
程序员文章站
2024-02-10 14:08:46
代码如下:
import java.io.bufferedreader;
import java.io.dataoutputstream;
import ja...
代码如下:
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 net.sf.json.jsonobject; public class interfacerequest { //模拟向腾讯云发送接口 //接口 private final static string url = "https://console.tim.qq.com/v4/im_open_login_svc/account_import?"; /** * @param args * @throws ioexception */ public static void main(string[] args) throws ioexception { // todo auto-generated method stub //连接服务器 httpurlconnection connection = connection(url); dataoutputstream out = new dataoutputstream( connection.getoutputstream()); jsonobject obj = new jsonobject(); obj.element("identifier", "hehe"); system.out.println(obj.tostring()); // 向腾讯请求传入编码为utf-8格式的json数据 out.write(obj.tostring().getbytes("utf-8")); out.flush(); out.close(); //获得服务器返回的结果 bufferedreader reader = new bufferedreader(new inputstreamreader( connection.getinputstream())); string lines; stringbuffer sb = new stringbuffer(""); while ((lines = reader.readline()) != null) { lines = new string(lines.getbytes(), "utf-8"); sb.append(lines); } reader.close(); } public static httpurlconnection connection(string url ) throws ioexception { url url = new url(url); httpurlconnection connection = (httpurlconnection) url.openconnection(); connection.setdooutput(true); connection.setdoinput(true); connection.setrequestmethod("post"); connection.setusecaches(false); connection.setinstancefollowredirects(true); connection.setrequestproperty("content-type", "application/x-www-form-urlencoded;charset=utf-8"); connection.connect(); return connection; // todo auto-generated method stub } }
以上这篇java以json格式向后台服务器接口发送请求的实例就是小编分享给大家的全部内容了,希望能给大家一个参考,也希望大家多多支持。