java以json格式向后台服务器接口发送请求的实例
代码如下:
importjava.io.BufferedReader; importjava.io.DataOutputStream; importjava.io.IOException; importjava.io.InputStreamReader; importjava.net.HttpURLConnection; importjava.net.URL; importnet.sf.json.JSONObject; publicclassInterfaceRequest{ //模拟向腾讯云发送接口 //接口 privatefinalstaticStringURL="https://console.tim.qq.com/v4/im_open_login_svc/account_import?"; /** *@paramargs *@throwsIOException */ publicstaticvoidmain(String[]args)throwsIOException{ //TODOAuto-generatedmethodstub //连接服务器 HttpURLConnectionconnection=connection(URL); DataOutputStreamout=newDataOutputStream( connection.getOutputStream()); JSONObjectobj=newJSONObject(); obj.element("Identifier","hehe"); System.out.println(obj.toString()); //向腾讯请求传入编码为UTF-8格式的json数据 out.write(obj.toString().getBytes("UTF-8")); out.flush(); out.close(); //获得服务器返回的结果 BufferedReaderreader=newBufferedReader(newInputStreamReader( connection.getInputStream())); Stringlines; StringBuffersb=newStringBuffer(""); while((lines=reader.readLine())!=null){ lines=newString(lines.getBytes(),"utf-8"); sb.append(lines); } reader.close(); } publicstaticHttpURLConnectionconnection(StringURL )throwsIOException{ URLurl=newURL(URL); HttpURLConnectionconnection=(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(); returnconnection; //TODOAuto-generatedmethodstub } }
以上这篇java以json格式向后台服务器接口发送请求的实例就是小编分享给大家的全部内容了,希望能给大家一个参考,也希望大家多多支持毛票票。