get 请求方法
public class ForGetRequest { public static Boolean sendParam(String path,Map<String,String> map) throws IOException{ StringBuilder sb = new StringBuilder(path); sb.append("?"); for(Map.Entry<String, String> entry:map.entrySet()){ sb.append(entry.getKey()+"="+entry.getValue()+"&"); } sb.deleteCharAt(sb.length()-1); System.out.println(sb.toString()); URL url = new URL(sb.toString()); HttpURLConnection conn = (HttpURLConnection) url.openConnection(); conn.setRequestMethod("GET"); conn.setReadTimeout(5*1000); if(conn.getResponseCode()==200){ return true; }else{ return false; } } }
post请求方法1
public class SendMessage { //通过HttpClient组件进行post请求。SSL。 public static boolean sendMsgFromHttpClient(Map<String,String> map,String path,String encoding) throws IOException{ List<NameValuePair> list = new ArrayList<NameValuePair>(); for(Map.Entry<String, String> entry:map.entrySet()){ list.add(new BasicNameValuePair(entry.getKey(), entry.getValue())); } UrlEncodedFormEntity form = new UrlEncodedFormEntity(list,encoding); HttpPost post = new HttpPost(path); post.setEntity(form); DefaultHttpClient client = new DefaultHttpClient(); HttpResponse request = client.execute(post); if(request.getStatusLine().getStatusCode()==200){ return true; } return false; } //这种post不是ssl,但请求速度比上面方法快 public static boolean postMsg(Map<String,String> map,String path,String encoding) throws IOException{ //Content-Type: application/x-www-form-urlencoded //Content-Length: 15 StringBuilder sb = new StringBuilder(); if(map!=null && !map.isEmpty() ){ for(Map.Entry<String, String> params:map.entrySet()){ sb.append(params.getKey()).append("=").append(params.getValue()).append("&"); } sb.deleteCharAt(sb.length()-1); } byte[] b = sb.toString().getBytes(); URL url = new URL(path); HttpURLConnection conn = (HttpURLConnection) url.openConnection(); conn.setDoOutput(true); conn.setRequestMethod("POST"); conn.setReadTimeout(5000); conn.setRequestProperty("Content-Type", "application/x-www-form-urlencoded"); conn.setRequestProperty("Content-Length",String.valueOf(b.length)); OutputStream out = conn.getOutputStream(); out.write(b); out.flush(); out.close(); if(conn.getResponseCode()==200){ return true; } return false; } }