1 // 转换编码 2 public static String encodeParameters(String parameterValue) 3 throws UnsupportedEncodingException { 4 if (parameterValue != null && parameterValue.length() > 0) { 5 byte[] iso = parameterValue.getBytes("ISO-8859-1"); 6 if (parameterValue.equals(new String(iso, "ISO-8859-1"))) { 7 parameterValue = new String(iso, "UTF-8"); 8 return parameterValue; 9 } 10 } 11 return parameterValue; 12 }
上代码为一个常用的字符串编码格式转换、建议在访问之前先用此方法将数据转码一次,保证编码格式无误
1 /** 2 * 使用post方法访问url 3 * @param url_str 4 * @param data_str 5 * @return url返回的结果集 6 */ 7 public static String operate(String url_str, String data_str) { 8 String result = "";// 结果集 9 String sc = ""; // 中间提取流中一行的数据 10 System.out.println("准备请求:" + url_str + "?" + data_str);// 查看完整url 11 OutputStreamWriter out = null; 12 BufferedReader br = null; 13 try { 14 URL url = new URL(url_str); 15 // 打开跟url之间的连接 16 HttpURLConnection con = (HttpURLConnection) url.openConnection(); 17 // 设置可以发送数据 18 con.setDoOutput(true); 19 // 设置可以接收数据 20 con.setDoInput(true); 21 // 设置post方式请求 22 con.setRequestMethod("POST"); 23 /* con.setRequestMethod("GET"); //设置get方式请求 */ 24 // 使用OutputStreamWriter获取URLConnection对象对应的输出流 ,采用默认编码格式 25 out = new OutputStreamWriter(con.getOutputStream(), "utf-8"); 26 // 发送请求数据 27 out.write(data_str); 28 // 避免缓冲造势、flush输出流中的缓冲区 29 out.flush(); 30 // 处理结果集,读取url的响应,采用默认编码格式 31 br = new BufferedReader(new InputStreamReader(con.getInputStream(), "utf-8")); 32 //通过中间变量、每次读取一行、读取到null时停止 33 while ((sc = br.readLine()) != null) { 34 result = result + sc;//拼接字符串 35 } 36 } catch (Exception e) { 37 System.out.println(e.getMessage());// 输出错误信息 38 } finally { 39 try { 40 if (out != null) { 41 out.close(); 42 } 43 if (br != null) { 44 br.close(); 45 } 46 } catch (IOException ex) { 47 System.out.println(ex.getMessage()); 48 } 49 } 50 // 打印返回结果 51 System.out.println("返回结果:" + result); 52 return result;//返回结果集 53 }
url_str 指url地址、 data_str 指需要发送的串