public static String doPostJson(String urlStr, Map<String, String> heads, String jsonStr) { try{ URL url = new URL(urlStr); HttpURLConnection connection = ((HttpURLConnection) url.openConnection()); connection.setDoInput(true); connection.setDoOutput(true); connection.setUseCaches(false); connection.setConnectTimeout(5000); connection.setRequestMethod("POST"); connection.setRequestProperty("Charset", "UTF-8"); //connection.setRequestProperty("Content-Type", "application/json-rpc"); connection.setRequestProperty("Content-Type", "application/x-www-form-urlencoded"); if (heads != null){ for(Map.Entry<String, String> head : heads.entrySet()){ connection.setRequestProperty(head.getKey(), head.getValue()); } } byte[] sendData = jsonStr.getBytes("UTF-8"); connection.setFixedLengthStreamingMode(sendData.length); connection.connect(); OutputStream out = connection.getOutputStream(); //out.write(sendData, 0, sendData.length); out.write(sendData); out.flush(); out.close(); InputStream input = connection.getInputStream(); StringBuffer sb = new StringBuffer(); byte[] buffer = new byte[512]; int len; while ((len = input.read(buffer)) != -1) { sb.append(new String(buffer, 0, len)); } input.close(); connection.disconnect(); return sb.toString(); }catch(Exception e){ Log.e("System.out", Log.getStackTraceString(e)); } return ""; } /** * 执行一个Http Get 请求,返回请求响应的HTML * @param url * 请求的URL地址 * @param heads * 请求时要设置的http头信息,没有设为null * */ public static String doGet(String url, Map<String, String> heads) { HttpResponse httpResponse = null; try { // 第1步:创建HttpGet对象 HttpGet httpGet = new HttpGet(url); if (heads != null){ for(Map.Entry<String, String> head : heads.entrySet()){ httpGet.addHeader(head.getKey(), head.getValue()); } } // 第2步:使用execute方法发送HTTP POST请求,并返回HttpResponse对象 httpResponse = new DefaultHttpClient().execute(httpGet); int statusCode = httpResponse.getStatusLine().getStatusCode(); if (statusCode == 200) { // 第3步:使用getEntity方法获得返回结果 String result = EntityUtils.toString(httpResponse.getEntity()); //System.out.println(result); return result; } } catch (Exception e) { Log.e("System.out", "Exception: "+Log.getStackTraceString(e)); } return null; }
http://hi.baidu.com/yezhonglu/item/ad7b6aa6b1cb021a030a4d37
80,471
社区成员
91,385
社区内容
加载中
试试用AI创作助手写篇文章吧