Http请求小结
1、Http请求:get方式
public void httpGet(String url,Map<String,Object> map) { try { String joint = parseMap(map); if(!TextUtils.isEmpty(url)) { url = url+"?"+joint; } URL newUrl = new URL(url);//创建URL //打开网络连接 HttpURLConnection conn = (HttpURLConnection)newUrl.openConnection(); conn.setRequestMethod("GET");//设置请求方式 InputStream is = conn.getInputStream();//获取输入流(读取流) BufferReader reader = new BufferReader(new InputStreamReader(is)); StringBuffer buffer = new StringBuffer(); if(2000 == conn.getResponseCode()) {//判断响应状态 String msg = null; while(null != (msg = reader.readLine())) {//读取返回数据 buffer.append(msg); } } Log.d("result",buffer.toString()); is.close();//关闭输入流 conn.disconnect();//关闭网络连接 } catch(MalformedURLException e) { e.printStackTrace(); } catch(IOException e) { e.printStackTrace(); } }
解析传入参数:
public String parseMap(Map<String,Object> map) { String result = ""; try { if(null == map) { return result; } for(String key : map.keySet()) { result = result + key + "=" + URLEncoder.encode(map.get(key).toString(),"UTF-8")+"&"; } if(!TextUtils.isEmpty(result)) { result = result.substring(0,result.length() - 1); } } catch(UnsupportedEncodingException e) { e.printStackTrace(); } return result; }
2、Http请求 :post方式
关于Content-Type类型特别说明,相关连接http://blog.csdn.net/blueheart20/article/details/45174399
public void httpPost(String url,String jsonObject) { URL newUrl = null; try { if(null == url) { return; } newUrl = new URL(url); HttpURLConnection conn = (HttpURLConnection)newUrl.openConnection(); conn.setRequestMethod("POST");//设置请求方式 conn.setInput(true);//设置允许输入 conn.setOutput(true);//设置允许输出 conn.setConnectTimeout(30000);//设置连接主机超时(单位:毫秒) conn.setReadTimeout(30000);//设置从主机读取数据超时(单位:毫秒) conn.setRequestProperty("Content-Type","application/json");//设置请求头体格式 conn.setRequestProperty("Charset","UTF-8");//设置请求体编码 conn.setRequestProperty("Content-Length",String.valueOf(jsonObject.getBytes().length));//设置请求体长度 OutputStream os = conn.getOutputStream();//获取输出流(写入流) os.write(jsonObject.getBytes());//输出数据 os.flush(); InputStream is = conn.getInputStream(); BufferReader reader = new BufferReader(new InputStreamReader(is)); StringBuffer buffer = new StringBuffer(); String msg = null; while(null != (msg = reader.readLine())) { buffer.append(msg); } Log.d("result",buffer.toString()); is.close(); conn.disconnect(); } catch (MalformedURLException e) { e.printStackTrace(); } catch (UnsupportedEncodingException e) { e.printStackTrace(); } catch (ProtocolException e) { e.printStackTrace(); } catch (IOException e) { e.printStackTrace(); } }