欢迎来到天天文库
浏览记录
ID:34723325
大小:59.64 KB
页数:8页
时间:2019-03-10
《httpurlconnection简单用法》由会员上传分享,免费在线阅读,更多相关内容在工程资料-天天文库。
1、http://blog.csdn.net/anyoneking/archive/2010/01/11/5177927.aspxHttpURLConnection为javaAPI提供的一种Rest访问的方式。其支持对Post,Delete,Get,Put等方式的访问。以下为对于HttpURLConnection对Post等方式访问的一段代码。viewplaincopytoclipboardprint?1.package com.sw.study.urlConnection; 2. 3.import java.io.BufferedRead
2、er; 4.import java.io.InputStreamReader; 5.import java.io.OutputStream; 6.import java.net.HttpURLConnection; 7.import java.net.URL; 8.import java.net.URLConnection; 9.import java.util.HashMap; 10.import java.util.Map; 11. 12.public class URLConnectionUtil { 13.
3、 14. private static final String SERVLET_POST = "POST" ; 15. private static final String SERVLET_GET = "GET" ; 16. private static final String SERVLET_DELETE = "DELETE" ; 17. private static final String SERVLET_PUT = "PUT" ; 18. 19. private static
4、 String prepareParam(Map paramMap){ 20. StringBuffer sb = new StringBuffer(); 21. if(paramMap.isEmpty()){ 22. return "" ; 23. }else{ 24. for(String key: paramMap.keySet()){ 25. String value = (S
5、tring)paramMap.get(key); 26. if(sb.length()<1){ 27. sb.append(key).append("=").append(value); 28. }else{ 29. sb.append("&").append(key).append("=").append(value); 30. } 31.
6、} 32. return sb.toString(); 33. } 34. } 35. 1. public static void doPost(String urlStr,Map paramMap ) throws Exception{ 2. URL url = new URL(urlStr); 3. HttpURLConnection conn = (HttpURLConnection)url.openCon
7、nection(); 4. conn.setRequestMethod(SERVLET_POST); 5. String paramStr = prepareParam(paramMap); 6. conn.setDoInput(true); 7. conn.setDoOutput(true); 8. OutputStream os = conn.getOutputStream(); 9. os.write(paramStr.toStr
8、ing().getBytes("utf-8")); 10. os.close(); 11. 12.
此文档下载收益归作者所有