String sendPost(String jsonStr, String path)\x0d\x0athrows IOException {\x0d\x0abyte[] data = jsonStr.getBytes()\x0d\x0ajava.net.URL url = new java.net.URL(path)\x0d\x0ajava.net.HttpURLConnection conn = \x0d\x0a(java.net.HttpURLConnection) url.openConnection()\x0d\x0aconn.setRequestMethod("POST")\x0d\x0aconn.setConnectTimeout(5 * 1000)// 设置连接超时
时间为5秒 \x0d\x0aconn.setReadTimeout(20 * 1000)// 设置读取超时时间为20秒 \x0d\x0a// 使用 URL 连接进行输出,则将 DoOutput标志
设置为 true\x0d\x0aconn.setDoOutput(true)\x0d\x0a \x0d\x0aconn.setRequestProperty("Content-Type", "text/xmlcharset=UTF-8")\x0d\x0a//conn.setRequestProperty("Content-Encoding","gzip")\x0d\x0aconn.setRequestProperty("Content-Length", String.valueOf(data.length))\x0d\x0aOutputStream outStream = conn.getOutputStream()// 返回写入到此连接的输出流\x0d\x0aoutStream.write(data)\x0d\x0aoutStream.close()//关闭流\x0d\x0aString msg = ""// 保存调用http服务后的响应信息\x0d\x0a// 如果请求响应码是200,则表示成功\x0d\x0aif (conn.getResponseCode() == 200) {\x0d\x0a// HTTP服务端返回的编码是UTF-8,故必须设置为UTF-8,保持编码统一,否则会出现中文乱码\x0d\x0aBufferedReader in = new BufferedReader(new InputStreamReader(\x0d\x0a(InputStream) conn.getInputStream(), "UTF-8"))\x0d\x0amsg = in.readLine()\x0d\x0ain.close()\x0d\x0a}\x0d\x0aconn.disconnect()// 断开连接\x0d\x0areturn msg\x0d\x0a}如果是已经有了URL的
接口URL url = new URL(接口)
创建链接对方接口对象
HttpURLConnection conn = (HttpURLConnection) url.openConnection()
设置请求属性
conn.setRequestProperty("accept", "*/*")
conn.setRequestProperty("connection", "Keep-Alive")
conn.setRequestProperty("user-agent", "Mozilla/4.0 (compatibleMSIE 6.0Windows NT 5.1SV1)")
设置是否向httpUrlConnection输出,设置是否从httpUrlConnection读入
conn.setDoOutput(true)
conn.setDoInput(true)
最后断开链接,保证速度
conn.disconnect()
基本就这样用需要更多的就要自己看api了
评论列表(0条)