java中post時中文亂碼


http://blog.chinaunix.net/uid-12348673-id-3335300.html

 

設置流的編碼,就避免了亂碼

public static String post(String path,String params) throws Exception{
 HttpURLConnection httpConn=null;
 BufferedReader in=null;
 //PrintWriter out=null;
 try {
  URL url=new URL(path);
  httpConn=(HttpURLConnection)url.openConnection();
  httpConn.setRequestMethod("POST");
  httpConn.setDoInput(true);
  httpConn.setDoOutput(true);
  System.out.print("params="+params);
 //utf-8
  PrintWriter ot = new PrintWriter(new OutputStreamWriter(httpConn.getOutputStream(),"utf-8")); 
  ot.println(params);
  ot.flush();
  //out=new PrintWriter(httpConn.getOutputStream());
  //out.println(params);
  
  //out.flush();

  //讀取響應
  if(httpConn.getResponseCode()==HttpURLConnection.HTTP_OK){
   StringBuffer content=new StringBuffer();
   String tempStr="";
   //utf-8
   in=new BufferedReader(new InputStreamReader(httpConn.getInputStream(),"utf-8"));
   while((tempStr=in.readLine())!=null){
    content.append(tempStr);
   }
   return content.toString();
  }else{
	  
   throw new Exception("請求出現了問題!");
   
  }
 } catch (IOException e) {
  e.printStackTrace();
 }finally{
  in.close();
 // out.close();
  httpConn.disconnect();
 }
 return null;
}

  


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM