首页 诗词 字典 板报 句子 名言 友答 励志 学校 网站地图
当前位置: 首页 > 教程频道 > 其他教程 > 互联网 >

httpclient(1)

2013-11-04 
httpclient(一)java net包里的方式PrintWriter out nullURL httpurl new URL(url)HttpURLConnection

httpclient(一)
java net包里的方式

PrintWriter out = null;URL httpurl = new URL(url);HttpURLConnection httpConn = (HttpURLConnection) httpurl.openConnection();httpConn.setRequestMethod("POST");httpConn.setDoOutput(true);httpConn.setDoInput(true);out = new PrintWriter(httpConn.getOutputStream());out.print(xml);out.flush();out.close();Util.convertStreamToString(httpConn.getInputStream(), "GBK");



get方式
HttpClient httpclient = new DefaultHttpClient();HttpGet request = new HttpGet();request.setURI(new URI(url));HttpResponse response = httpclient.execute(request);

post方式
HttpPost httpRequset = new HttpPost(url);HttpEntity httpentity = new StringEntity(xml, "GBK");  httpRequset.setEntity(httpentity);HttpClient httpclient = new DefaultHttpClient();httpentity = httpclient.execute(httpRequset).getEntity();if (httpentity != null) {System.out.println(Util.convertStreamToString(httpentity.getContent(), "GBK"));}httpRequset.abort();


/** *  * @description 转化输入流为指定编码的字符串 * @throws UnsupportedEncodingException  */public static String convertStreamToString(InputStream is, String charsetName)throws UnsupportedEncodingException {BufferedReader reader = new BufferedReader(new InputStreamReader(is,charsetName));StringBuilder sb = new StringBuilder();String line = null;try {while ((line = reader.readLine()) != null) {sb.append(line + "\n");}} catch (IOException e) {e.printStackTrace();} finally {try {is.close();} catch (IOException e) {e.printStackTrace();}}return sb.toString();}



key-value键值对的post方式
        // HttpPost连接对象          HttpPost httpRequset = new HttpPost("http://10.0.2.2:8080/dem/");          // 使用NameValuePair来保存要传递的Post参数          List<NameValuePair> params = new ArrayList<NameValuePair>();          // 添加要传递的参数          params.add(new BasicNameValuePair("par", "asdf"));          try {              // 设置字符集              HttpEntity httpentity = new UrlEncodedFormEntity(params, "gb2312");              // 请求httpRequset              httpRequset.setEntity(httpentity);              // 取得HttpClient              HttpClient httpClient = new DefaultHttpClient();              // 取得HttpResponse              HttpResponse httpResponse = httpClient.execute(httpRequset);  

热点排行