httpclient4列子

public class ApiUtil {
   
   protected static Logger log = LoggerFactory.getLogger(ApiUtil.class);
   public static final String GET_UID_URL = "http://xxxxx.com/";
   public static final int OK_CODE = 200;

   @SuppressWarnings("unused")
   public static int methodName(String name){
       if (name == null || name.trim().isEmpty()){
           return 0;
       }
       HttpClient httpclient = null;
       InputStream instream = null;
       try {
           String url = GET_UID_URL + URLEncoder.encode(name, "utf8");
          
           httpclient = new DefaultHttpClient();
           //超时设置
           HttpParams params = httpclient.getParams();
           HttpConnectionParams.setConnectionTimeout(params, 3000);
           HttpConnectionParams.setSoTimeout(params, 3000);
          
           HttpGet httpget = new HttpGet(url);
          
           HttpResponse response = httpclient.execute(httpget);
           int statusCode = response.getStatusLine().getStatusCode();
           if (statusCode == OK_CODE){
               HttpEntity entity = response.getEntity();
              
               instream = entity.getContent();
               if (entity != null) {
                   BufferedReader reader = new BufferedReader(new InputStreamReader(instream));
                   String ret = reader.readLine();
                   return Integer.parseInt(ret);
               }
           }else{
               return 0;
           }
          
       }catch(Exception e) {
           log.error("name error {}", new Object[]{e});
           return 0;
       }finally {
           if (instream != null){
               try {
                   instream.close();
               } catch (IOException e) {
                   log.error("name instream.close error {}", new Object[]{e});
               }
           }
           if (httpclient != null){
               httpclient.getConnectionManager().shutdown();
           }
       }
       return 0;
   }
}

你可能感兴趣的:(httpclient)