java使用SAE中文分词服务

使用java调用SAE中文分词服务

采用post方式提交context值

分词后使用json返回分词数组

代码如下:
 public static String sendRequest(String context){
 
  BufferedReader in = null;
  StringBuffer result = new StringBuffer();
  HttpURLConnection httpConnection =null;
  try {

   //分词请求地址
   URL url = new URL("http://segment.sae.sina.com.cn/urlclient.php?encoding=UTF-8&word_tag=1");
   httpConnection = (HttpURLConnection) url.openConnection();
   httpConnection.setUseCaches(false);
   httpConnection.setDoOutput(true);
   httpConnection.setRequestMethod("POST");
   httpConnection.setDoOutput(true);
   httpConnection.setDoInput(true);
   httpConnection.setReadTimeout(10000);
   httpConnection.setConnectTimeout(10000);
    byte[] b = context.getBytes("utf-8");
    httpConnection.getOutputStream().write(b, 0, b.length);
    httpConnection.getOutputStream().flush();
    httpConnection.getOutputStream().close();
    in = new BufferedReader(new InputStreamReader(httpConnection.getInputStream(),"utf-8"));
    while (true) {
               String line = in.readLine();
               if (line == null) {
                 break;
               }
               else {
                   result.append(line);
               }
             }
    System.out.println("******:"+result.toString());

   
  } catch (IOException  e) {
   // TODO Auto-generated catch block
   e.printStackTrace();
  } finally{
            try {
                if(in!=null){
                    in.close();
                }
                if(httpConnection!=null){
                 httpConnection.disconnect();
                }
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
  return result.toString();

  
  
 }

猜你喜欢

转载自tianziking.iteye.com/blog/2048354